Created
January 11, 2013 15:21
-
-
Save nikodemrafalski/4511445 to your computer and use it in GitHub Desktop.
Finds index of nearest number in a sorted decimals array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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