Compare multiple cycles and move the maximum number to the top of each comparison. During each loop, find the maximum value in the remaining variables and then reduce the query range. After multiple loops, the array is sorted.
The code is as follows:
/**
* Bubble sort
*
* Principle: compare multiple cycles and move the maximum number to the top of each comparison. During each loop, find the maximum value in the remaining variables and then reduce the query range. After multiple loops, the array is sorted.
*/
Function sort_bubble ($ list)
{
$ Len = count ($ list );
If (empty ($ len) return $ list;
For ($ I = 0; $ I <$ len; $ I ++)
{
For ($ j = $ I + 1; $ j <$ len; $ j ++)
{
$ Flag = '';
If ($ list [$ I]> $ list [$ j]) // from small to large
// If ($ list [$ I] <$ list [$ j]) // from large to small
{
$ Tmp = $ list [$ I];
$ List [$ I] = $ list [$ j];
$ List [$ j] = $ tmp;
$ Flag = "change ";
}
Echo implode (',', $ list). $ flag ."
";
}
Echo "-------------------------
";
}
Return $ list;
}
$ List = array );
$ List = sort_bubble ($ list );