I know this question was asked before. I read the following question: how to determine if the kth largest element of the heap is greater than x but I have further questions. I did not want to post in a thread that old. So:
Given a number x
and a number k
, check if x
is bigger than the k
-th smallest element in O(k)
.
The previous question does the same thing, but with max-heaps and smaller than. That is not the problem.
Consider a binary min-heap:
1
2 3
12 17 50 90
23,18 80,88 51,52 91,92
Let x
be 19 and k
be 6.
The 6th smallest element is 18.
If I do the algorithm in the other thread, it would check as follows:
1+,2+,12+,23,18+,17+,80,88,3+
The +
signals when the counter is increased.
How does the algorithm know that 18 is the k
-th smallest number, not 3?
And why does the checking of 23, 80 and 88 not interfere with O(k)
?