Home >Backend Development >PHP Tutorial >PHP implementation of bubble sort_PHP tutorial
[php]
/*
*Bubble sorting is a brute force method with a time complexity of N squared. It can be improved: if the positions of elements are not exchanged after comparing the list, then the list has been sorted and the algorithm stops
*/
function bubble_sort($arr){
$len=count($arr);
for($i=0;$i<$len-1;$i++){
for ($j=0; $j < $len-i-1; $j++) {
If($arr[$j+1]<$arr[$j]){
$tmp=$arr[$j];
$arr[$j]=$arr[$j+1];
$arr[$j+1]=$tmp;
}
}
Return $arr;
}
$arr=array(3,8,2,5,6);
$res=bubble_sort($arr);
print_r($res);
?>
$len=count($arr);
for($i=0;$i<$len-1;$i++){
for ($j=0; $j < $len-i-1; $j++) {
if($arr[$j+1]<$arr[$j]){
$tmp=$arr[$j];
$arr[$j]=$arr[$j+1];
$arr[$j+1]=$tmp;
}
}
}
return $arr;
}
$arr=array(3,8,2,5,6);
$res=bubble_sort($arr);
print_r($res);
?>