Pregunta

I have a question about finding the kth largest element using a min-heap. The algorithm is as follows:

  1. We take the first k elements and build a minheap

  2. Let Sk be the smallest element in S.

  3. Look at a new element, from the remaining n-k elements.

  4. If the new element is larger than Sk, then it replaces it in S, and reorder the heap.

  5. S then will have a new smallest element.

  6. After looking at all the other elements Sk is the answer

I do not understand this algorithm. For example, let the numbers be 1, 2, 3, 4. We want to find 4th largest, which is 4. But when we use the algorithm, we take first 4 elements, build the minheap, and Sk is 1.

What am I doing wrong? I would appreciate if someone could help. Thanks

¿Fue útil?

Solución

I think your confusion is with the terminology. The largest element in the sequence 1, 2, 3, 4 is the number 4. The second-largest element is 3, the third-largest is 2, and the fourth-largest is 1. Since the algorithm returns 1, it works correctly.

However, 4 is the kth-smallest element in the sequence. If you want to find the kth-smallest element, you can just swap the min-heap with a max-heap and make the appropriate tweaks to the algorithm.

Hope this helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top