I have a binary heap with $n$ elements. I want to get the $k$ largest elements in this heap, in $O(k \log k)$ time. How do I do it?
(Calling deletemax $k$ times yields a $O(k \log n)$ complexity. I'm looking for $O(k \log k)$.)
The only solution I've come up with so far is the following:
You have 2 arrays. A(largest numbers), B(to analyze).
- It's easy to find the largest number, since we already have the heap. We move the maximum number to $A$.
- We move the maximum number's children to $B$
- We sort $B$
- We add the children of the largest number in $B$
- Remove the largest number from B (first element of $B$), add it to $A$
- Repeat the procedure until there are $k$ elements in $A$
The question here is: do we get a $O(k \log k)$ complexity? we obviously repeat the procedure $k$ times, but does the sorting take $O(\log k)$ time? I guess if the array is already sorted it's easy to insert a new number in $O(\log k)$ time. However, will the length of array B always be less than or equal to $k$?
Can you please confirm or deny my solution? If it's wrong, can you please help me find a solution to this problem?