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:
Post a Comment