Bubble Sorting Algorithm

Recently, I had the need to re-order posts in wordpress according to a specifically numbered tag. Unfortunately, WordPress doesn’t let you order post output by tag since that’s usually what categories are used for. So I decided to capture all the output into a multidimensional array. However, I still needed some way to sort the array and asort(); wasn’t the answer. Instead I used something called a Bubble sort algorithm to do the heavy lifting.

The code…

for($x = 0; $x < $array_size; $x++) {
  for($y = 0; $y < $array_size; $y++) {
    if($ran[$x] < $ran[$y]) {
      $hold = $ran[$x];
      $ran[$x] = $ran[$y];
      $ran[$y] = $hold;
    }
  }
}

It works by running through the entire array, comparing each element to every element in the array. If it encounters a situation where the item’s value is less than the next item it stores it in a temporary variable and sets the variable to the larger version. Then replaces the previously larger version with the smaller amount. If you don’t get it, here’s a great video to explain it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.