I was just recently playing around and got to thinking I coded a bubble sort algorithm in everything from C to Scheme but not in PHP. So I took a good college try at it and this is what I came up with:
/*
Author: Anthony Wlodarski
Created On: 1/18/10
Bubble Sort Function
*/
// Pre: valid array
// Post: returns an array sorted with the bubble sort algorithm
function bubble_sort($values = array())
{
if(count($values) < 2)
{
return $values;
}
// we have an array with at least two items to sort
$total_number_of_values = count($values);
// for each element we must loop through the loop
for($i = 0; $i < $total_number_of_values-1; $i++)
{
// inside each loop we must iterate through the entire array to "bubble"
// our elements
for($j = 0; $j < $total_number_of_values-1; $j++)
{
if($values[$j] > $values[$j+1])
{
$temp = $values[$j];
$values[$j] = $values[$j+1];
$values[$j+1] = $temp;
}
}
}
return $values;
}
$elements = array();
$total_elements = rand(0, 256);
for($a = 0; $a < $total_elements; $a++)
{
$elements[$a] = rand(0, PHP_INT_MAX);
}
$sorted_elements = bubble_sort($elements);
You can take a look at the algorithm in action here: http://hash.anthonyw.net/tests/bubblesort.php