How to efficiently sort and filter a large iterator Given an huge iterator (millions of random elements) and asked to obtain the top 10 elements in descending/ascending order. 
What is an efficient way or algorithm to do this?

NOTE: The iterator size is to huge and cannot be all loaded into memory and in-place sorting done. (I need a different approach)

I have a simple implementation in Python (sorting an iterators containing hash maps), but it's not efficient

def sort(iterator, sort_key, count):
    result = []
    for idx, row in enumerate(iterator):
        if idx &lt; count:
            result.append(row)
        elif idx == count:
            result.sort(key=lambda x: x[sort_key])
            if row[sort_key] &gt; result[-1][sort_key]:
                result.append(row)
                result.sort(key=lambda x: x[sort_key])
                result = result[:count]
        else:
            if row[sort_key] &gt; result[-1][sort_key]:
                result.append(row)
                result.sort(key=lambda x: x[sort_key])
                result = result[:count]

    return result
You can use a max-heap or min-heap. If you want to find the top $k$ elements, use a min-heap. Start by inserting the first $k$ elements. For every subsequent element, compare it to the root of the min-heap. If the new element is smaller, continue to the next element. Otherwise, remove the root and insert instead the new element, operations which can be done in $O(\log k)$. In total, this is an $O(n\log k)$ algorithm.