Bubble SortingAlgorithmIs the most basic sorting algorithm, which is an exchange sorting algorithm.
Bubble Sorting Process
Imagine the sorted array R [1 .. n] vertical erect, each data element is considered as a bubble with weight, according to the principle that light bubbles cannot be under heavy bubbles, scanning array R from bottom up, when a light bubble that violates this principle is scanned, it is made to "float" (SWAP position), so repeatedly until the last two bubbles are light, and the severe bubbles are down.
Performance Analysis
If the initial status of the record sequence is "positive", the Bubble sorting process only needs to sort the sequence. During the sorting process, only n-1 comparisons are required and records are not moved. Otherwise, if the initial status of the record sequence is "backward", You need to perform n (n-1)/2 comparisons and record movement. Therefore, the total time complexity of Bubble Sorting is O (n * n ).
Bubble sort implementation
The implementation varies slightly depending on the Scanning direction.
CodeAs follows:
Void bubblesort_1 (int A [], int size) {for (INT I = 0; I <size-1; I ++) {for (Int J = size-1; j> I; j --) {if (a [J-1]> A [J]) {int temp = A [J-1]; A [J-1] = A [J]; A [J] = temp ;}}}}
Step 1 Optimization
In the code above, if a layer of loops in a scan does not execute the exchange, it means that the array has all sequences and no scanning is required. Therefore, when a tag is added, it is marked every time a switch occurs. If there is no tag after a loop, it indicates that the sorting has been completed.
Void bubblesort_2 (int A [], int size) {bool bswaped = true; For (INT I = 0; I <size-1; I ++) {// reset to falsebswaped = false each time; for (Int J = size-1; j> I; j --) {if (a [J-1]> A [J]) {int temp = A [J-1]; A [J-1] = A [J]; A [J] = temp; bswaped = true ;}} // if the last scan does not exchange, it indicates that the array is fully ordered and the loop if (bswaped) break is exited ;}}
Step 2 Optimization
On the basis of step 1 optimization, let us further think: If R [0 .. i] is already an ordered interval. The last scan interval is R [I .. n], remember that the last time the switch was executed at lastswappos during the last scan, then lastswappos is between I and N, and it is not difficult to find R [I .. the lastswappos] interval is also ordered, otherwise this interval will be exchanged; so the next scan interval can be set by R [I .. n] reduced to [lastswappos .. n].
Void bubblesort_3 (int A [], int size) {for (INT I = 0; I <size-1; I ++) {int lastswappos = I; for (Int J = size-1; j> lastswappos; j --) {if (a [J-1]> A [J]) {int temp = A [J-1]; A [J-1] = A [J]; A [J] = temp; lastswappos = I ;}}}}