title: Find closest index by difference with BinarySearch
body: <p>I have a sorted array of about 500,000 ints. Currently I am selecting the correct index by taking the differences between my target int, and all of the elements, and then sorting by the minimum difference using LINQ (very inefficient).</p>
  
  <p>I'd like to be able to do something very similar with BinarySearch.</p>
  
  <p>Given:</p>
  
  <pre><code>Pos Value
  0   10
  1   20
  2   30
  4   50
  5   60
  </code></pre>
  
  <p>If I want to find the closest value for value 24 I would want the index returned to be 1.</p>
  
  <p>Given:</p>
  
  <pre><code>int index = myArray.BinarySearch(values, 24);
  if (index &lt; 0)
      index = ~index;
  </code></pre>
  
  <p>This returns 2 since it gives the next element in line, instead of the closest. Is it possible to write an IComparer that would return the closest index?</p>
  
  <p>Given values:</p>
  
  <pre><code>Value ExpectedReturn
  20    1
  24    1
  25    2
  26    2
  30    2
  </code></pre>
  
  <p>I am trying to make this as fast as possible. Everything I have done so far in LINQ has been sub par to what I think can be achieved with a well done binary search. Thank you for the input.</p>