2010-02-05 32 views
3

所以,我正在尋找最有效的方法來按值排序一堆pairs<string, float>,因爲我需要獲得大量對的3個最高的條目。我的自然反應是使用sortedList,但顯然它只按鍵進行排序,我不能使用反轉列表解決方案,因爲我知道字符串是唯一的,但浮點數可能不是。.NET - 有效的對排序<key, value>按值

我忽略了任何簡單而有效的解決方案嗎?

+4

爲什麼不用你使用sortedList自定義比較器進行排序嗎? – anthares 2010-02-05 17:48:33

+0

您使用的是什麼C#版本? – 2010-02-05 17:50:03

+0

我使用.NET框架3.5 – brokencoding 2010-02-05 17:54:13

回答

13

如果您只需要知道前三個值,則不需要對整個列表進行排序 - 只需執行一次通過,即可在任意時間存儲前三個值。這將使它成爲O(n)而不是O(n log n)...但是你必須自己實現它。

如果你滿意爲O(n log n)的,雖然,最簡單的方法很可能是使用LINQ:

var ordered = pairs.OrderBy(pair => pair.Value).Take(3).ToList(); 

它可能不會太難以執行喜歡的事:

public static IEnumerable<TSource> TakeTop<TSource, TKey> 
    (this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector, 
    int count) 

它可能具有O(n * count)的複雜性。如果我有一點更多的時間我會做的樂趣...

+0

O(1)或胸圍! – 2010-02-05 19:03:58

+0

爲什麼不是O(0)? :) – LBushkin 2010-02-05 19:18:33

+0

要獲得更多樂趣,請嘗試執行O(n +(count-1)* log n)算法。 – 2010-02-05 20:24:52

2

你可以使用LINQ:

yourDictionary.OrderBy(kv => kv.Value).Take(3); 

我不知道的效率做的,但肯定是短期和表現力。

0

我不知道這是否是最有效的,但你可以嘗試做:

List<KeyValuePair<string,float>> myList = new List<KeyValuePair<string,float>>(): 

... //adding whatever... 

myList.Sort(delegate(KeyValuePair<string,float> pair1, KeyValuePair<string,float> pair2) { return pair1.Value.CompareTo(pair2.Value); }); 
0

如果你想有一個平衡red-black tree,你可以找到一個在C5

using Bag = C5.TreeBag<C5.KeyValuePair<string, float>>; 
using Comparer = C5.DelegateComparer<C5.KeyValuePair<string, float>>; 

... 

var bag = new Bag(new Comparer(
    (pair1, pair2) => 
    pair1.Value == pair2.Value ? 
    pair1.Key.CompareTo(pair2.Key) : 
    // inverted because you need the highest entries 
    pair2.Value.CompareTo(pair1.Value))); 

... 

var topN = bag.Take(N).ToList(); 

檢索(和其他所有操作)具有O(log n)複雜性。

0

這裏容斯的擴展方法跟進是一個實現

public static IEnumerable<TSource> TakeTop<TSource, TKey> 
    (this IEnumerable<TSource> source, 
    Func<TSource, TKey> keySelector, 
    int count) 
{ 
    var top = source.Take(count).OrderBy(keySelector).ToArray(); 
    var last = count-1; 
    foreach(var item in source.skip(count)) 
    { 
    if(keySelector(top[last]) < keySelector(item)) 
    { 
     top[last] = item; 
     //depending on count this might be faster as buble sort 
     top = top.OrderBy(keySelector).ToArray(); 
    } 
    } 
    return top; 
} 

considere它的草稿我已經在SO文本:)「實施」它

0

的替代解決方案上面 - 作爲值插入到地圖中尋找高值,因爲添加了新的鍵/值對,並在構建地圖時構建前三名(當然,您並沒有將地圖從當然外部遞交給地圖)