I have a sorted list of key / value pairs and want to find values ​​adjacent to the new key

I have a list of key / value pairs (will probably use a SortedList) and I will not add new values.

Instead, I will use the new keys to get bounding values. For example, if I have the following key / value pairs:

(0,100) (6, 200), (9, 150), (15, 100), (20, 300) 

and I have a new key of 7, I want it to return 200 and 150, because 7 is between 6 and 9.

If I give 15, I want it to return 100 and 100 (because 15 is exactly 15). I want something like binary search.

thank

+3
source share
2 answers

List<T>.BinarySearch:

var keys = new List<int>(sortedList.Keys);
int index = keys.BinarySearch(target);
int lower;
int upper;
if (index >= 0) {
  lower = upper = index;
}
else {
  index = ~index;
  upper = index < keys.Count ? index : index - 1;
  lower = index == 0 ? index : index - 1;
}

Console.WriteLine("{0} => {1}, {2}", 
  target, sortedList[keys[lower]], sortedList[keys[upper]]);

List<T>.BinarySearch . msdn :

" List<T>, , - , , , , Count."

, , , "" . , , , . - , .

+2

, - List<t>.BinarySearch, , , IComparer ( aux, ).

+2

Source: https://habr.com/ru/post/1734817/


All Articles