The last one said the choice of the principle of sorting, this time we say the principle of bubble sort
In fact, the bubble sort and the selection sort are all very simple sorting methods.
This article describes the following:
Sorting principle
Algorithm implementation (JAVA)
Testing phase
Algorithm analysis
Sorting principle
Each loop iterates through an array, and if the previous element's value is greater than (or less than) the next element, the position is swapped. If each pair of elements is not exchanged after iterating through the array, the array is proved to be ordered. The outer loop of the bubbling sort is the do-while Loop, and the inner loop is the for loop. A temporary Boolean variable value is required to determine whether a position exchange is made within each inner loop.
Algorithm implementation
The code is short:
1. Outer circulation
public static void bubbleSort(int[] a) { int n = a.length; boolean changed; //判断是否已交换 do { changed = false; }while(changed); }
2. Inner Loop
for (int i = 0; i < n - 1; i++) { if(a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; changed = true; } }
This is how the entire sorted block of code is:
public static void bubbleSort(int[] a) { int n = a.length; boolean changed; //判断是否已交换 do { changed = false; for (int i = 0; i < n - 1; i++) { if(a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; changed = true; //表示已有元素交换位置 } } }while(changed); }
The maximum value for the For loop is set to N-1 because there is a A[n + 1] in the IF statement, otherwise the array subscript will be out of bounds.
Testing phase
The same test data:
public static void main(String[] args){ int[] a = new int[10]; for (int i = 0; i < a.length; i++) { a[i] = (int)(Math.random()*100); System.out.print(a[i] + " "); } System.out.println(); bubbleSort(a); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } }
Select several sets of test results:
Algorithm Analysis 1. Characteristics
- Think and think, can only say simple
2. Complexity of Time
3. Stability
- When exchanging element group elements, a temporary variable is needed to help swap elements, so the spatial complexity is O (1)
Bubble sort that's it, and the next article will tell you about the insertion sort.
"Algorithm" sort (ii) bubble sort