Bubble sort is a simple sorting algorithm working by stepping through all unsorted objects one by one, comparing them to the next one and swapping them if they are in the wrong order. Then doing this over and over again, until no objects are swapped.
This is one of the worst performing sorting algorithms, but implementation is very simple. Here’s a sample PHP block that does the trick.
// array $a contains unsorted objects do { $swapped = false; for($i = 0; $i < count($a) - 1; $i++) { if($a[$i] > $a[$i+1]) { list($a[$i], $a[$i+1]) = array($a[$i+1], $a[$i]); $swapped = true; } } } while($swapped);
PHP’s internal sort() function, which uses Quicksort, is around 1 000 times faster then this code when sorting 1 000 objects. When sorting 10 000 objects, PHP’s Quicksort is over 10 000 times faster.
