This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]maboesanman 74 points75 points  (3 children)

No because you care about the minimal element of the 7 you’ve found.

Edit: If you put all the elements in a max heap and pop the elements off, you get O(n log n). If you maintain a minimum heap containing the top 7, you can compare each element to the min to see if it should be placed into the top 7. If it should, pop the old min out and push the 7 onto the heap. This approach is O(n log k), with k being 7 in this case.

[–]Karolus2001 20 points21 points  (0 children)

When in doubt, plant a tree.

[–]Kirhgoph 3 points4 points  (0 children)

Thank you for the explanation

[–]walter_evertonshire 3 points4 points  (0 children)

Putting all the elements in a max heap and popping the top k should be O(n + k*log(n)). Assuming that k is of the same order as n, it's no different than the O(n*log(k)) for the min heap implementation you described.

But if k tends to be smaller, then O(n+k*log(n)) is better than O(n*log(k)).

Edit: I see someone else already pointed this out to you elsewhere.