An Interesting Sort

Consider the following algorithm for sorting a list:

  1. Shuffle the elements into random order
  2. Iterate through the list to check if it is sorted.
  3. If it isn't sorted, go back to step 1.

Assume that shuffling and checking the list are both linear operations in terms of the number of elements in the list.

Let O(f(n)) be the average case performance of this algorithm, where n is the number of elements in the list. What is f(4)/f(1) ?

For example: if the average case performance is O( n 2 n^2 ), then f ( n ) = n 2 f(n) = n^2 , and f ( 4 ) / f ( 1 ) = 16 / 1 = 16 f(4)/f(1) = 16/1 = 16 .


The answer is 96.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

The answer is 96 .

A list of size n has n ! n! possible permutations, so the chance of a random shuffle producing the correct order is 1 / n ! 1/n! .

This is a geometric distribution with p = 1 / n ! p = 1/n! . The mean value of the probability distribution of the number of Bernoulli trials needed for the first success is 1 / p 1/p . For this case, on average it will take n ! n! shuffles before the we reach a successful one.

Since shuffling and checking the list are both linear operations, the final average case performance is O ( n × n ! ) O(n \times n!) . f ( n ) = C ( n × n ! ) f(n) = C*(n \times n!) , for some coefficient C. f ( 4 ) / f ( 1 ) = 96 f(4)/f(1) = 96 .

Thank you for this interesting problem.

Michael Ng - 6 years, 6 months ago
David Ng
Oct 13, 2014

This sorting algorithm is best known as Bogosort. As described, if the elements in the list are not already sorted, the algorithm randomly shuffles the contents of the list, until it is sorted. This means, the best case would be O(n), and the worst case would be O(infinity).

If we take into account the possible permutations, we get n!, which would be the average shuffles before we reach a sorted list in this scenario. Multiply this value with n for the time it takes to traverse the list and f(n) becomes n*n!. Substitute values 4 and 1 into this equation to get 96.

Or also: bogosort, blort sort, bort sort, monkey sort, random sort, stochastic sort e drunk man sort. Font: Wikipedia :D

Drop TheProblem - 6 years, 6 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...