For the improvement of bubble sort, thanks to Morewindows (Microsoft's most valuable expert), to provide me with such a good idea, I just wrote a full Java version.
/** * * @author Fly/public class Bubblesort {//No thought write exchange sort//not bubble sort, compare not adjacent element public int[] Bubblesort (
Int[] a) {int size = A.length; for (int i = 0; i < size; i++) {for (int j = i + 1; j < size; J +) {if (A[i] > A[j]
) {int temp = A[i];
A[i] = A[j];
A[J] = temp;
}} return A;
}//Bubble sort public int[] BubbleSort1 (int[] a) {int size = A.length; for (int i = 0; i < size-i. i++) {for (int j = 0; J < size-i-1; + +) {if (A[j] & Gt
A[j + 1]) {int temp = a[j];
A[J] = a[j + 1];
A[j + 1] = temp;
}} return A; }//Improved bubble sort//Improvement point://1) Add flag bit, Mark final swap position, remove unnecessary exchange operation;//2 if the current loop does not exchange data, the description has finished sorting, removing unnecessary comparisons; public int[] B UbbleSort2 (Int[] a) {int size = A.length;
for (int i = 0; i < size-1 i++) {//Make a sign bit int flag = i; for (int j = 0; J < size-i-1; j +) {//If the order is incorrect, record the flag bit that needs to be exchanged, and then swap the position once (A[j] > A[j
+ 1]) {flag = J; }///If the flag bit is replaced with the instruction data Order No if (flag > I) {///exchange data int te
MP = A[i];
A[i] = A[flag];
A[flag] = temp;
Adjust the starting position again, since the element (if any) after the sign bit is definitely the order i = flag;
If the flag bit does not change, that indicates that the data is all in the same place, jump out of the loop directly} else {break;
} return A;
public void PrintArray (int[] a) {for (int i:a) {System.out.print (i + ",");
} System.out.println ();
public static void Main (string[] args) {int[] a = {2, 3, 1, 5, 7, 8, 9, 0, 11, 10, 12, 13, 14, 4, 6}; Bubblesort bubblesort = new Bubblesort ();
Bubblesort.printarray (a);
Bubblesort.printarray (Bubblesort.bubblesort (a));
Bubblesort.printarray (Bubblesort.bubblesort1 (a));
Bubblesort.printarray (Bubblesort.bubblesort2 (a)); }
}