如何获取列表的前10个排序项而不排序整个列表

时间:2010-06-28 19:40:35

标签: algorithm sorting

问题是我有一个100万个数字的列表,但我只想要排序列表中的第一个10,但我不想对整个列表进行排序?这可能吗?

2 个答案:

答案 0 :(得分:6)

是。您只需运行一次列表,并存储十个最小的数字。算法将是O(n)(实际上,O(n * 10)最坏情况)

Foreach (list)
 - Check if current item is smaller than the biggest item in the sorted Array[10]
 - If so, put the current item at the right spot (sorted) in the array (insertionsort), bumping away the biggest item.

答案 1 :(得分:6)

您想要的是优先级队列。将每个号码插入优先级队列。如果队列的大小超过10,则删除最小(或最大)的值。最后留在队列中的值是10个最大(或最小)。

如果队列是使用Heap实现的,那么这可能是一种非常有效的算法。