Bogo Sort In PHP

23rd June 2018

I came across this sorting algorithm the other day called 'bogo sort'. This is a sort of joke sorting algorithm that is highly ineffective at actually sorting arrays. The name comes from the word 'bogus'.

Here is how it works.

  1. Take an array.
  2. Shuffle it.
  3. If the array sorted then stop.
  4. If the array is not sorted then return to step 2.

As you can see, this isn't so much a sorting algorithm, more of a game of chance. Due to the random nature of the sort you might need to wait a very long time before the array is actually sorted.

Here is an implementation of a bogo sort in PHP.

  1. /**
  2.  * Sort an array using a bogo sort algorithm.
  3.  *
  4.  * @param array $array
  5.  * The array to sort.
  6.  *
  7.  * @return array
  8.  * The sorted array.
  9.  */
  10. function bogoSort($array) {
  11. // Assume array is unsorted.
  12. $sorted = FALSE;
  13.  
  14. while ($sorted == FALSE) {
  15. // Keep running until the array is sorted.
  16. for ($i = 0; $i < count($array) - 1;++$i) {
  17. // Loop through the array and check that it has been sorted.
  18. if ($array[$i] > $array[$i + 1]) {
  19. // The array has not been sorted, so break out of the check loop.
  20. $sorted = FALSE;
  21. break;
  22. }
  23. // If we get to this point then the array is sorted.
  24. $sorted = TRUE;
  25. }
  26.  
  27. if ($sorted) {
  28. // Array is sorted, return it.
  29. return $array;
  30. }
  31.  
  32. // Shuffle the array.
  33. shuffle($array);
  34. }
  35. }

So why make this? Just for fun really. I had a good chuckle the first time I heard about this sorting algorithm so I had to have a god at implementing one. This algorithm is often used for educational purposes as a worst case scenario. The bogo sort is usually slower than a unidirectional bubble sort.

The mechanism of the bogo sort means that the length of the array dramatically increases the time taken to sort it. Sorting an array of under 5 items takes a few seconds (still quite a long time really). Sorting an array of more than 10 items takes a couple of minutes. I didn't test any more than 10 items in an array as I would be waiting for a very long time to sort.

As a quick test I decided to see how long the bogo sort actually took. 

  1. $times = [];
  2.  
  3. for ($i = 0; $i <= 10; ++$i) {
  4. $time_start = microtime(true);
  5.  
  6. $array = range(0, 10);
  7. shuffle($array);
  8. $array = bogoSort($array);
  9.  
  10. $time_end = microtime(true);
  11. $times[] = $time_end - $time_start;
  12. }
  13. echo 'Total time: ' . (array_sum($times)) . 's Average time per sort: ' . (array_sum($times) / count($times)) . 's';

After quite a long time this is printed out.

Total time: 897.42127370834s Average time per sort: 81.583752155304

Sorting 10 arrays of 10 items takes a full 15 minutes.

Add new comment

The content of this field is kept private and will not be shown publicly.