2013-03-22 104 views
0

我正在寫東西來記錄跨對象的各種方法的性能。我想找到前10個最慢的時間。因此,我想要一個類似排序列表的東西,例如在我的情況下。因此,每當我有新的時間,我只是插入它,並命令它。它會被修復,所以在我插入第五次(假設它在下面的例子中被限制爲5)後,列表將不會增長,但它會將其插入列表中,並刪除最小值。固定分類列表/數據結構

E.g.

var topTen = new XXX<double>(5); 

XXX.Insert(1); 
XXX.Insert(3); 
XXX.Insert(2); 
XXX.Insert(6); 
XXX.Insert(4); 
XXX.Insert(5); 

/* 
topTen[0] is 6 
topTen[1] is 5 
topTen[2] is 4 
topTen[3] is 3 
topTen[4] is 2 
*/ 

我打算寫的東西,但我只是想知道如果在.NET中有什麼在那裏了。

+0

不是內置類。但是你可能會發現'MyPriorityQueue'實現[here](http://pastebin.com/NHDdrbYV)有用。它完全正是你想要做的。 – I4V 2013-03-22 22:40:44

回答

0

通常情況下,你可以用堆做這樣的事情。例如:

var heap = new BinaryHeap<int>(); 

for (int i = 0; i < 1000; ++i) 
{ 
    var time = GetTimeSomehow(); 
    if (heap.Count < 5) 
    { 
     heap.Insert(time); 
    } 
    else if (time > heap.Peek()) 
    { 
     // the new value is larger than the smallest value on the heap. 
     // remove the smallest value and add this one. 
     heap.RemoveRoot(); 
     heap.Insert(time); 
    } 
} 

這限制大小爲5,當你做,你可以爲了獲得前5名:

while (heap.Count > 0) 
{ 
    var time = heap.RemoveRoot(); 
    Console.WriteLine(time); 
} 

沒有在.NET中可用的堆數據結構框架。我後來發表了一篇簡單的文章。見A Generic BinaryHeap Class

0

試試這個(未經測試):

int listLength = 5;

List<int> list = new List<int>(listLength+1); 

void VerifyTime(int time) { 
    list[listLength] = time; 
    var i = listLength; 
    while (listLength>0 && list[listLength] < list[listLength-1]) 
    swap(list, listLength, listLength-1); 
} 

void swap (List<int> l, int a, int b) { 
    var temp = l[a]; 
    l[a] = l[b]; 
    l[b] = temp; 
} 

對於ListLength的任何小值,它應該工作得很好。