Home > Article > Backend Development > Sorting Algorithm Bubble Algorithm_PHP Tutorial
Bubble algorithm is a simple sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time and swapping them if they are in the wrong order. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the array through swapping.
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)
Bubble algorithm improvement method one:
If no exchange occurs in a certain loop, it means that the data has been sorted and the program will jump out directly.
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;
}