We never run out of sorting algorithms. Here is a strange sorting algorithm called the Sleep Sort .
1 2 3 4 5 6 7 8 9 |
|
Which of the following best describes the time complexity for sleep sort?
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.
First, note that the algorithm is hardware-dependent, because forking a new process is not an instantaneous operation, and switching between running threads also takes time. In fact, if there are enough elements in the array so that forking a new process takes more than n 1 seconds, the algorithm fails; consider the sequence 1 , 0 , 0 , … , 0 , where the process printing 1 will finish before the last process printing 0 starts. So now assume that forking a new process takes a very short time, say ϵ < n 1 seconds, and that all threads can run simultaneously without any impact on time (say they are running on parallel processors). We'll also consider that the sequence consists of non-negative integers only, because we don't want to deal with time travel involving sleeping for -1 seconds. (We can generalize this so that the sequence consists of multiples of a certain number τ ; we then need ϵ < n τ . We cannot have unrestricted rational or real numbers because they might be separated by less than ϵ .)
Consider the sequence a 1 , a 2 , … , a n . The first element takes ϵ seconds to fork, plus a 1 seconds to wait. The second element takes 2 ϵ seconds to fork (it needs to wait for the first element to finish forking first), plus a 2 seconds to wait. In general, the i -th element takes i ϵ seconds to fork, plus a i seconds to wait. Since all elements are running simultaneously, the time taken will be the maximum among these: max ( i ϵ + a i ) . Because ϵ < n 1 , we have i ϵ < 1 , thus a larger a i will definitely take more time than a smaller a i . Among those with the largest a i , those with larger i will take more time (because i ϵ is larger when i is larger). Thus suppose the maximum a i is achieved by a k (and if tied, take the largest k ). The running time is k ϵ + a k seconds.
Thus k ϵ + a k = O ( n ) + O ( max a i ) = O ( max a i + n ) .
The answer is not O ( max a i ) because it's possible to have a i = 0 for all i . In this case, max a i = 0 , so by definition of big O notation, there should be some c satisfying k ϵ + a k ≤ c ⋅ max a i , or k ϵ ≤ c ⋅ 0 = 0 , contradiction. If the input is restricted to positive integers only, then the answer O ( max a i ) is more accurate (we can pick c = 2 ).