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)