I have a sorted array of about 500,000 ints. I am currently choosing the right index, taking the differences between my target int and all the elements, and then sorting by the minimum difference using LINQ (very inefficient).
I would like to do something very similar to BinarySearch.
Given:
Pos Value 0 10 1 20 2 30 4 50 5 60
If I want to find the closest value to a value of 24, I would like the index to return equal to 1.
Given:
int index = myArray.BinarySearch(values, 24); if (index < 0) index = ~index;
This returns 2 because it gives the next element in the string, not the closest. Is it possible to write IComparer that will return the closest index?
Indicated values:
Value ExpectedReturn 20 1 24 1 25 2 26 2 30 2
I am trying to do this as quickly as possible. All that I have done so far in LINQ has been an approach to what, in my opinion, can be achieved with a well-done binary search. Thanks for the input.
optimization c # binary-search
jsmith
source share