Reputation: 215
Let an algorithm which get unsorted array with the size of n
. Let a number k<=n
. The algorithm prints the k-smallest numbers from 1 to k (ascending). What is the lower bound for the algorithm (for every k)?
Omega(n)
Omega(k*logn)
Omega(n*logk)
Omega(n*logn)
Now, from my understanding, if we want to find a lower-bound to an algorithm we need to look at the worst-case. If that the case, then obviously the worst-case is when k=n
. We know that sorting an array is bounded by Omega(nlogn)
so the right answer is #4.
Unfortunately, I am wrong and the right answer is #5.
Why?
Upvotes: 1
Views: 204
Reputation: 636
Lets try with Linear time:
O(n)
. And use that element as pivot for the quick sort.array[i] <= k
and array[i]>k
. This would take O(n)
timearray[i]<=k
(which has k elements) and do counting sort, which will obviously take O(k+K)O(k)
Total time = O(n)+O(k+K)+O(k)
= O(n+k+K)
Here, k is the number of elements which are smaller or equal to K
Upvotes: 1
Reputation: 178411
It can be done in O(n + klogk)
.
O(klogk)
It is easy to see this solution is optimal - cannot get better than O(klogk)
factor because otherwise for assigning k=n you could sort any array better, and a linear scan at least is a must to find the required elements to be printed.
Upvotes: 2