繁体   English   中英

固定排序列表/数据结构

[英]Fixed Sorted List / Data structure

我正在写一些东西来记录跨对象的各种方法的性能。 我想找到最慢的10个时间。 因此,我想要一个固定的排序列表,例如在我的案例10中。因此,只要有新时间,我就插入它并对其进行排序。 它将得到修复,因此在我插入第5次之后(假设下面的示例将其限制为5),该列表将不会增长,但只会将其插入列表中,并删除最小值。

例如

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中是否已经有任何东西。

通常,您对堆执行类似的操作。 例如:

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 Framework中没有可用的堆数据结构。 我不久前发表了一篇简单的文章。 请参见通用BinaryHeap类

试试这个(未试用):

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值,它应该都可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM