Yonatan Zunger (zunger) wrote,
Yonatan Zunger
zunger

A complete waste of time!

So a few days ago, I got an amusing idea for an interview question which I realized was totally pointless as an interview question, because it has no practical value whatsoever. So instead, I'm going to post it on my blog, as a way to help waste the time of all my CS friends. There is no prize whatsoever for a correct answer, except for the satisfaction of having avoided work for a while solved an amusing problem.

Here are two really bad ways to sort an array:
  1. Random sort: Repeatedly select a random permutation and apply it to the set. Stop when it becomes sorted.

  2. Brute-force sort: Iterate over the set of all permutations of N elements. Apply each in turn. If the list is now sorted, stop.

The question is: which of the two is less efficient, and (the trickier part) by how much?

(Clarification: For the latter, "how much" in terms of average [mean] time to sort. You can also average over a large number of possible inputs)
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 13 comments
This looks to me like sampling with and without replacement.

Iterating over all permutations is sampling without replacement. That's n choose 1, (in other words, there are n! permutations), and on average, we'll find the correct one halfway through. So it's O(n!), with a constant of .5.

Random iterations is sampling with replacement, and the sample space is again all the permutations So it becomes a geometric distribution with probability of success 1/n!, and the expected time to success is 1/(1/n!), or n!. (but without the reduced constant.)

So random permutations is twice as inefficient.

Going to peek now!
Foo. Am I really the first one to answer?
You are, and you win! :)
Woohoo! My math has not failed me. :)
Huh.
I mis-thunk this one.
On first read, it looked like Drunkard's Walk v. Iterative Brute Force, which I thought favored Drunkard's Walk.
Except that that's wrong, because the 'you'll find it halfway through' rule applies to Brute Force, while the random replacement isn't actually a Drunkard's Walk.