The title says it all; What is the most efficient way to find the log nth maximum number in a max heap with n elements?
ps: The text book I'm reading vaguely explained a solution with time complexity of O(lognloglogn)
by using another heap that I can't understand, can we do better than that?
Let H
be the original max-heap. Let H'
be another max-heap, initially empty, that operates on pairs (index, value)
of elements from the first heap and orders the pairs based on the second component.
H'.push(0, H[0])
count = ceil(log n)
while count > 0 do
(i, v) := H'.extract-max()
// takes O(log log n)
timeH'.push(2i+1, H[2i+1])
if H[2i+1]
exists // O(log log n)
timeH'.push(2i+1, H[2i+2])
if H[2i+2]
exists // O(log log n)
timecount := count - 1
v
The reason we have O(log log n)
bounds on running times of operations of H'
is that H'
contains at most log n
elements and each operation runs in time logarithmic in the number of elements of the heap, which is O(log log n)
.
The total running time is obviously O(log n log log n)
. I'm assuming the original max-heap H
is represented with an array.