Bubble sort in Java (reduces the number of comparisons)

Source: Internet
Author: User

 PackageYzhou.sort;Importjava.util.Arrays; Public classbubblesort{ Public Static voidMain (string[] args) {int[] arr =        { 9, 1, 2, 5, 4 };        Sort (arr);    System.out.println (arrays.tostring (arr)); }    //reduce the number of times per trip     Public Static voidSortint[] arr) {        Booleansorted =true; intLen =arr.length;  for(intj = 0; J < Len-1; J + +) {sorted=true; System.out.println ("First" + j + "Trip");  for(inti = 0; I < len-1-J; i++) {System.out.println ("No." + (i + 1) + "secondary"); if(Arr[i] > arr[i + 1])                {                    inttemp =Arr[i]; Arr[i]= Arr[i + 1]; Arr[i+ 1] =temp; Sorted=false;            } System.out.println (Arrays.tostring (arr)); }            if(sorted) { Break; }        }    }}

Boolean sorted = true; Role:

Bubble sort, for loop always compares the size between the two

First define a Boolean variable, assuming equal to true, meaning: Some data is sorted well, do not compare the

Int[] 1,2,3,4,6

1 comparison 2 sorted = true;

2 Comparison 3 sorted = true;

3 Comparison 4 sorted = true;

4 comparison 6 sorted = true;

When sorted = True, it means that these data have been sequenced, small on the left, large on the right, otherwise, if the condition is established, sorted = false;

Int[] 1,3,2,7,8

1 Comparison 3 sorted = true;

3 comparison 2 sorted = false;

.......

If condition is set, sorted = False, description, the current array, there is part of the data left greater than the right

Bubble sort in Java (reduces the number of comparisons)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.