I have seen a lot of Introduction to Bubble sorting, including teaching books. I personally feel that many of the descriptions are not very clear, or my personal understanding may be poor, however, the figure found on the Internet looks very clear. I hope it can help some friends. The Bubble sorting principle is to compare the adjacent numbers in the order of ascending to ascending or ascending to smallest, the largest or smallest number is switched to the last digit, and then compared and exchanged from the beginning until the last digit ends. The rest are similar examples.
You can also describe the bubble sort as follows:
Is to compare the keywords of the first record with those of the second record,
If the latter is smaller than the former, the second and third are compared, and so on.
Than the end of a trip, the largest one has been placed in the last position, so that you can compare the number of the previous N-1 recycling.
Stable, time complexity O (N ^ 2)
Instance: // Bubble sort (array sorting)
Function bubble_sort ($ array){
$ COUNT = count ($ array );
If ($ count <= 0) return false;
For ($ I = 0; $ I <$ count; $ I ++ ){
For ($ J = $ count-1; $ j> $ I; $ J -){
If ($ array [$ J] <$ array [$ J-1]) {
$ TMP = $ array [$ J];
$ Array [$ J] = $ array [$ J-1];
$ Array [$ J-1] = $ TMP;
}
}
}
Return $ array;
}
Bubble sorting principle