[Math] What algorithm can sort the first sqrt(n) elements of an array in O(n) time

algorithmsasymptotics

I want to partially sort an array of $n$ elements to get the first $\sqrt{n}$ elements sorted, and it has to be done in $O(n)$ time.

The complexity $O(n)$ seems to imply that it is necessary to go through the entire array, but when using a sorting algorithm in the first step of building a tree/heap by using heap sort, this and other $O(nlogn)$ algorithms are the fastest they can be when processing the entire $n$ elements.

Does this mean that I don't have to process all the numbers, and what kind of strategy can I use?

Best Answer

I'm not sure it can be done.

First of all, you have to look at all $n$ items.

Then, you have to keep the top $\sqrt{n}$ items. To find where an item that is in the top $\sqrt{n}$ places, you have to do $O(\log(\sqrt{n})) =O(\log(n)) $ comparisons. If the items are badly ordered, you will have to do this $n$ times.

This gives a worst case time of $O(n \log n)$.

If the items are will distributed, the placing in the top $\sqrt{n}$ might only be done $\sqrt{n}$ times. In this case, the placing would only take $O(\sqrt{n}\log(n))$ operations, so this would be $O(n)$.

Related Question