1. Basic Idea: arrange the unordered array r[1...n] vertically, scan the array r from bottom to top, compare the adjacent two elements, if the above element value is less than the value below, adjust the position of the two adjacent elements, and then continue to scan upward until the order is Sorted.
2. Sorting process:
(1) initialize: Read unordered array r[1...n]
(2) the first scan: from the bottom of the array R to scan upward, and then compare the adjacent two elements, if the value is found to be smaller on the above, then the position of the exchange of two Elements. Compare (r[n], r[n-1]), (r[n-1], r[n-2]) 、。。。 (r[2], r[1]), for each pair of elements (r[j], r[j+1]), if R[j+1].key < r[j].key, then Exchange r[j+1] and r[j] Content.
The first scan is complete, the element with the smallest key is r[1 in the first position].
(3) Section two scan: scan r[2...n], when the scan is complete, the key Sub-small element in the second position r[2]
finally, an ordered array can be obtained by n-1 scanning r[1...n]
Note: If a scan is found, no elements are exchanged for position, indicating that all elements are in an orderly state, and that the sequence can be stopped after the scan is Completed. therefore, you can introduce a Boolean exchange that resets Exchange to false before each scan, and if the sorting process (that is, The scanning Process) has an element exchange, set Exchange to True to check exchange after each scan is completed If Exchange is false, the algorithm is terminated and the next pass is no longer sorted.
3, the code is as Follows:
voidbubblesort (seqlist R) {inti,j; Boolean exchange; for(inti =1; I < n; i++) {exchange=false; for(j=n-1; J >= i; j--){if(r[j+1].key <R[j].key) {r[0]=r[j]; r[j]=r[j+1]; R[j+1]=r[0];exchange=TRUE;}if(!Exchange)return;}}}
The bubble sort is a stable sort, the worst time complexity is O (n^2), the best time complexity is O (n), the average time complexity is O (n^2), and the spatial complexity is O (1).
Pick to the programmer interview, infringement will be Deleted.
A big meta--bubble sorting algorithm for sorting algorithms