algorithmsortingbubble-sort

Can Bogo Sort Outperform Bubble Sort in Certain Scenarios?


In my recent comparison of the Bubble Sort and Bogo Sort algorithms, specifically analyzing their performance in sorting an array of length 9, Bubble Sort consistently exhibited faster sorting times (no surprises there!). However, I'm curious if there are any conceivable scenarios where Bogo Sort might unexpectedly outperform Bubble Sort in terms of sorting speed.


Solution

  • Of course it is.

    For Bogo Sort of a 9-element array, there is a 1-in-362880 chance that the correct ordering is generated on the first try.

    The worst case for Bubble Sort is when the original array is reverse-sorted. In that case, Bubble Sort of a 9-element array requires 36 swaps and at least 36 comparisons.

    The same array in Bogo Sort, if you are extremely lucky, requires only 1 comparison to realize it is not already sorted, at most 9 swaps to generate the random shuffling, and another 8 comparisons to verify that it is correctly sorted.

    So, Bubble Sort of a reverse-sorted 9-element array always requires 36 swaps and at least 36 comparisons, whereas there is a 0.0002755731922% chance that Bogo Sort can do it in 9 comparisons and at most 9 swaps.

    On the other hand, there is of course also an infinitesimally small chance that Bogo Sort will fail generate the correct sorting within a bounded amount of tries and thus run for an unbounded amount of time.