Skip to content

Instantly share code, notes, and snippets.

@nikodemrafalski
Created January 11, 2013 15:21
Show Gist options
  • Select an option

  • Save nikodemrafalski/4511445 to your computer and use it in GitHub Desktop.

Select an option

Save nikodemrafalski/4511445 to your computer and use it in GitHub Desktop.
Finds index of nearest number in a sorted decimals array.
private int FindNearestNumberIndex(decimal value, decimal[] array)
{
int index = Array.BinarySearch(array, value);
if (index >= 0)
{
return index; // direct match
}
int indexOfFirstHigherValue = ~index;
if (indexOfFirstHigherValue == 0)
{
return 0;
}
if (indexOfFirstHigherValue == array.Length)
{
return array.Length - 1;
}
decimal higher = array[indexOfFirstHigherValue];
decimal lower = array[indexOfFirstHigherValue - 1];
return Math.Abs(higher - value) < Math.Abs(lower - value)
? indexOfFirstHigherValue
: (indexOfFirstHigherValue - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment