Simple Script Bubble Sort an Array in PHP

Another common script is the bubble sort. Although I do not recommend using it as it is too slow as compared to the other sorting algorithms like merge sort and quick sort, it is worth knowing how it is done.

The basic idea is to compare every item in the array to every other item an swap them until they are all sorted.

<?php
function bubblesort($list) 
{
    $count = count($list);
    for ($i=0; $i<$count; $i++) 
        for ($j=0; $j<$count-$i-1; $j++) 
            if ($list[$j+1] < $list[$j]) 
                list($list[$j], $list[$j+1]) = array($list[$j+1],$list[$j]);
    return $list;
}
$unsorted = array(5,2,1,6,10,0,8,3,4,9,7);
print_r(bubblesort($unsorted));
?>

 

Leave a Reply