2013-03-22 107 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的任何小值,它应该工作得很好。