The bubble algorithm is a simple sorting algorithm. It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
Function BubbleSort ($ array ){
If (empty ($ array) |! Is_array ($ array ))
Return false;
$ Len = count ($ array)-1;
For ($ I = $ len; $ I> 0; $ I --){
For ($ j = 0; $ j <$ I; $ j ++ ){
If ($ array [$ j + 1] <$ array [$ j]) {
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j + 1];
$ Array [$ j + 1] = $ temp;
}
}
}
Return $ array;
}
Time Complexity: O (n * n)
Method 1 for improving the bubble algorithm:
If no exchange occurs in a loop, the data is sorted and the program jumps out.
Function BubbleSort2 ($ array)
{
If (empty ($ array) |! Is_array ($ array ))
Return false;
$ Len = count ($ array );
$ Ischange = false;
For ($ I = $ len-1; $ I> 0 &&! $ Ischange; $ I --)
{
$ Ischange = true;
For ($ j = 0; $ j <$ I; $ j ++)
{
If ($ array [$ j + 1] <$ array [$ j])
{
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j + 1];
$ Array [$ j + 1] = $ temp;
$ Ischange = false;
}
}
}
Return $ array;
}