2010-06-28 57 views

回答

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

您可以通過使用堆爲您的「列表」10來將該10變成基於lg的常量。:-) – corsiKa 2010-06-28 19:46:09

+0

O(n * 10)= O(n)。 – recursive 2010-06-28 20:11:42

+0

遞歸:offcourse,但是這表明,當數字10變得更高(比如說,你希望列表的一半排序)時,O會改變,而一個簡單的數組將不會。然後你需要一個更好的數據結構,比如glowcoder說。 – Konerak 2010-06-28 20:17:31

6

你想要的是優先級隊列。將每個號碼插入優先隊列。如果隊列大小超過10,則刪除最小(或最大)值。最後隊列中剩餘的值是10個最大(或最小)。

如果使用Heap實現隊列,那麼這可能是一個非常有效的算法。

相關問題