In C++ I was able to use std::map<double, T>
which is an ordered dictionary for its keys, but is a Red-Black tree which gives me O(lg n) for both insert and search. I was able to look up whether a value existed within some epsilon by using std::lower_bound and std::upper_bound together.
I have not been able to find the same thing while using C# 7+/.NET Core. Does such a thing exist?
In pseudocode, I'd like to do something like this
Map<float, T> map = ...
// key epsilon newValue
map.Insert(0.5f, 0.1f, someObj); // No values in the map, inserts fine
map.Get( 0.45f, 0.1f); // 0.45 +/- 0.1 contains 0.5, would return someObj
map.Get( 0.3f, 0.1f); // 0.3 +/- 0.1 does not include 0.5, it is not found
map.Insert(0.55f, 0.1f, anotherObj); // 0.55 +/- 0.1 includes 0.5, replace someObj
map.Insert(0.35f, 0.1f, anObj); // 0.35 +/- 0.1 doesn't overlap, insert new value
The way I'd have to do it would be to roll my own self-balancing binary search tree, but I'd rather not reinvent the wheel if such a thing exists.
I've been looking at SortedDictionary
, however its Keys
field is a collection so I can't jump around in it. Same issue for OrderedDictionary
, unless I missed something.
I may not be able to use a SortedList since there will be more insertions than lookups, and due to the random order I'm worried that I'll end up getting a lot of O(n) swaps that need to be done when insertions. I'm assuming a uniform distribution in my input (which is very likely the case because of the data I'm working with), which means the insertions towards the middle and the front would cause a lot of shifting if it implements it the way I think it does... which would give me on average a cost of n/2 insertions and leave me at O(n). At least with a binary search tree, I'm getting O(lg n). Therefore the good solution here may not be applicable.
Most importantly, this is an algorithm that is used in a very hot section of the code. Performance is extremely important, choosing something that is not fast will likely drastically damage the performance of the application. I really need O(lg n) or some novel way of doing this that I didn't think of before.