简体   繁体   中英

Fixed Sorted List / Data structure

I'm writing something to that logs the performance of various methods across objects. I want to find the top 10 slowest times. Hence I want something like a sorted list that's fixed, eg in my case 10. So whenever I've got a new time, I just insert it and it orders it. It will be fixed, so after i've inserted the 5th time (assuming its limited to 5 for the example below) then the list won't grow, but it will just insert it into the list, and remove the smallest value.

Eg

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
*/

I was going to write something for it but I was just wondering if there was anything out there already in .net.

Typically, you do something like this with a heap. For example:

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);
    }
}

That limits the size to 5, and when you're done you can get the top 5 in order:

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

There is no heap data structure available in the .NET Framework. I published a simple one a while back. See A Generic BinaryHeap Class .

Try this (untested):

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;
}

For any small value of ListLength it should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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