i starting from 0, Array [i] and array [i + 1], and if array [i]> array [i + 1], then the exchange position
After sorting through a maximum value will bubble up to the last one
public void bubbleSort ( int Array []) { for ( int I = 0; I <be array.length; I ++ ) { // Since Array [j] is compared with the array [j + 1], the last to be traversed bit j + 1 = array.length, so J <-be array.length. 1 for ( int J = 0; J <be array.length -. 1; J ++ ) { IF (Array [J]> Array [J +. 1 ]) { int TEMP = Array [J]; Array [J] = Array [J +. 1 ]; Array [J +. 1] = TEMP; } } } }
Optimization 1
Look at each traverse of the last
After the first pass, the maximum value of bit i is bubbled into
After the second pass, the second largest value is bubbled into the first bit i-1
After the third pass, the third largest value is bubbling to the second bit i-2
...
So after each of the last traverse again without having to compare
public void bubbleSort ( int Array []) { for ( int I = 0; I <array.length; I ++ ) { // each time after the last one is the maximum traversing, without re comparison, so to traverse array.length -1 position it for ( int J = 0; J <be array.length - I -. 1; J ++ ) { IF (Array [J]> Array [J +. 1 ]) { int TEMP = Array [J]; Array [J] = Array [J +. 1 ]; Array [J +. 1] = TEMP; } } } }
Optimization 2
If after a certain time through complete, the array has completed the sequencing, then do not continue traversal
public void bubbleSort(int array[]) { for (int i = 0; i < array.length; i++) { boolean isSorted = true;//标志是否已排序 for (int j = 0; j < array.length - i - 1; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; isSorted = false; } } if(isSorted) { break ; } } }
Optimization 3
After one pass through a last already ordered a large part, this part can now be done without sorting, such as [3, 2, 1, 6, 7, 8, 9, 10], from Array [3 the last position of the element exchange at] then that is orderly, we can finally recorded in each round of the sort that the boundary position disordered array
public void bubbleSort ( int Array []) { int sortBorder be array.length = -. 1; // boundary without the array int lastExchageIndex = 0; // record the last position exchanged for ( int I = 0; I <be array.length; I ++ ) { Boolean IsSorted = to true ; for ( int J = 0; J <sortBorder; J ++ ) { IF (Array [J]> Array [J +. 1 ]) { int TEMP = Array [J]; Array [J] = Array [J +. 1 ]; Array [J +. 1] =weather; isSorted = false ; lastExchageIndex = j; } } SortBorder = lastExchageIndex; ow (isSorted) { break ; } } }
Reference https://blog.csdn.net/wubingju93123/article/details/81215984