Reputation: 175
How would you find the k smallest elements from an unsorted array using quicksort (other than just sorting and taking the k smallest elements)? Would the worst case running time be the same O(n^2)?
Upvotes: 0
Views: 2235
Reputation: 1332
You could optimize quicksort, all you have to do is not run the recursive potion on the other portions of the array other than the "first" half until your partition is at position k. If you don't need your output sorted, you can stop there.
Warning: non-rigorous analysis ahead.
However, I think the worst-case time complexity will still be O(n^2). That occurs when you always pick the biggest or smallest element to be your pivot, and you devolve into bubble sort (i.e. you aren't able to pick a pivot that divides and conquers).
Another solution (if the only purpose of this collection is to pick out k min elements) is to use a min-heap of limited tree height ciel(log(k))
(or exactly k nodes). So now, for each insert into the min heap, your maximum time for insert is O(n*log(k))
and the same for removal (versus O(n*log(n)
) for both in a full heapsort). This will give the array back in sorted order in linearithmic time worst-case. Same with mergesort.
Upvotes: 1