Bubble Sort
by levans, Feb 17, 2020, 12:05 AM
A long time ago, when the Earth was green, there were more types of animals than you've ever seen. I also had a high school programming class in which we learned about bubble sort, along with a bunch of other things. In college, we learned many more algorithms. The problem, though, is that I have not had much need to use any of these algorithms in my day to day working. That's OK. The point of much of this learning was how to think about algorithms, not the algorithm itself. But, since I've basically forgotten all the original algorithms, I've decided to go back to high school and re-learn some of these things. First up is something really simple, a sorting algorithm called Bubble Sort. Bubble sort is slow, but it's pretty neat in that, unlike many algorithms, it's extremely easy to visualize what is going on. It's simply going through a list of items, comparing them to the next item, and swapping the two if they are out of order. Repeat. Repeat. Repeat. Then when all the items are sorted, break out. I'd draw pictures if I weren't lazy, but I personally find it a lot easier just to read code.
/**
* Implementation of bubble sort algortihm, generally considered
* one of the slowest, but most understandable sorting algorithms.
*
* @param array $list An array of elements to sort.
*/
function bubbleSort($list) {
// Get size of list, subtracting 1 because arrays are 0 indexed.
$size = sizeof($list) - 1;
do {
// For each iteration, we reset the $swapped variable.
// When the entire list has been iterated over, and
// no swaps have occured, we know the list is sorted
// and we end there.
$swapped = false;
// Loop through each item comparing it to the next item
// in the list. We us < $size instead of <= $size, because
// we'd otherwise try to compare the last element to something
// outside of the array, which will lead to an out of
// bounds error.
for ($i = 0; $i < $size; $i++) {
// Get element values
$current = $list[$i];
$next = $list[$i + 1];
// Swap if out of order. Change to > if you want descending
if ($next < $current) {
$list[$i + 1] = $current;
$list[$i] = $next;
// Set flag indicating a swap has been made
$swapped = true;
}
}
} while ($swapped);
return $list;
}
$x = [1, 8, 7, 2, 10, -8, 39, 12];
print_r(bubbleSort($x));
This post has been edited 3 times. Last edited by levans, Mar 23, 2020, 6:46 AM