The Bubble sorting algorithm is one of the simplest and most direct sorting methods.
After each traversal, a maximum (or minimum) number is bubble.
Pre-defined sorting type. To verify whether the sorting method is correct, we simply perform sorting detection on 10 elements. As follows:
# Define maxsize 10 typedef struct {int R [maxsize + 1]; int length;} sqlist; void swap (sqlist * l, int I, Int J) {int temp = L-> r [I]; L-> r [I] = L-> r [J]; L-> r [J] = temp ;}
Note: All sorting in this article is in ascending order.
The first one is a bit like the Bubble Sorting Algorithm for sorting:
This method is not a traditional bubble method. Traditionally, the bubble method compares and exchanges Adjacent Elements in the sorting array. This method compares and exchanges each element with the remaining elements. The Code is as follows:
Void bubblesort0 (sqlist * l) {int I, j; for (I = 0; I <L-> length-1; I ++) {for (j = I + 1; j <L-> length; j ++) {If (L-> r [I]> L-> r [J]) {swap (L, I, j );}}}}
2. Traditional Bubble sorting method:
Void bubblesort1 (sqlist * l) {int I, j; for (I = 0; I <L-> length; I ++) {for (j = 0; j <L-> length-I-1; j ++) {If (L-> r [J]> L-> r [J + 1]) {swap (L, J, J + 1 );}}}}
Third: improved Bubble sorting method
We know that in the Bubble Sorting Algorithm, even if the subsequent element sequence is already ordered and no comparison is required, the Bubble Sorting Algorithm will still be executed to the end. Can we improve it to avoid additional comparison operations when such a situation occurs?
You can set a flag. When no data is exchanged, the order is sorted. Then the algorithm stops running. The Code is as follows:
Void bubblesort2 (sqlist * l) {int I, j; bool flag = true; for (I = 0; I <L-> length & flag; I ++) {flag = false; For (j = 0; j <L-> length-1-i; j ++) {If (L-> r [J]> L-> r [J + 1]) {swap (L, J, J + 1 ); flag = true ;}}}}
References: big talk Data Structure