Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding nearest value in a SortedDictionary

I have a SortedDictionary

 SortedDictionary<int, CPUOptimizationObject> myDict;

Now I want to find the first value above X. I can do something like this

foreach (var iKey in MyDict.Keys)
{
   if (iKey >= thresholdKey)
   {
       foundKey = iKey;
       break;
   }
}

but this isn't good performance wise.
Any better suggestion?
(is there a method for that in the collections something like Binary search for SortedDictionary ?)

like image 372
Bick Avatar asked Dec 09 '13 15:12

Bick


1 Answers

While, in theory, finding the smallest item that is larger than a given value is an operation that can be performed efficiently on a Binary Search Tree (which is what a SortedDictionary is implemented as) SortedDictionary does not expose the means for you to perform such a search on that data type.

You would need to use a different implementation of a Binary Search Tree in order to efficiently perform such a search, while still using the same type of data structure. There are no suitable .NET types; you would need to use a 3rd party implementation (of which there are quite a few out there).

like image 67
Servy Avatar answered Oct 17 '22 15:10

Servy