Friday, November 9, 2007

PHP Bubble sort

Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which means the list is sorted.

example: 5 1 4 2 8 - unsorted array 1 4 2 5 8 - after one pass 1 2 4 5 8 - sorted array

The algorithm gets its name from the way smaller elements "bubble" to the top (i.e. the beginning) of the list via the swaps. (Another opinion: it gets its name from the way greater elements "bubble" to the end.) Because it only uses comparisons to operate on elements, it is a comparison sort. This is the easiest comparison sort to implement.


PHP implementation:


function bubbleSort( $array )
{

for( $i=1; $i < count($array); $i++ )
// move smaller from two elements up until reach current position
for( $j = (count($array)-1); $j >= $i; $j-- )
if( $array[$j-1] > $array[$j] )
{
$tmp = $array[$j-1];
$array[$j-1] = $array[$j];
$array[$j] = $tmp;
}

return $array;
}

No comments: