Suppose I have a heap of arbitrary size n, and I want to find the 6 (or some number, whatever) largest elements in the heap. The heap is, for reasons that I'm not going to go into, represented by an array.
The lazy way out, obviously, is to just remove the maximum element 6 (or however many) times, copy the results into another array, and then reinsert said elements back into the heap.
Is there a more efficient/faster algorithm to get the largest numbers?
I'm going to assume you aren't retarded enough to be asking this for a max-heap, so I'll answer for a min-heap.
Consider a general heap with k = 2m - 1 + r elements, where r < 2m.
Take the set S of all leaf nodes in the heap. That is, all elements with array index greater than (2m - 1 + r)/2. We take T as the n greatest elements in S by using an efficient selection algorithm.1]. If |S| < n simply add all elements of S to T.
While there are two elements in T with the same parent, and neither of these two elements is the smallest element in T, check if their parent is greater than the least element in T. If so; add it to T. If |T| > n remove the least element in T.
______________ 1. Knuth, Donald. The Art of Computer Programming, Volume 3: Sorting and Searching, Third Edition. Addison-Wesley, 1997. Section 5.3.3: Minimum-Comparison Selection, pp.207–219.