title: Binary Search Closest Value c#
body: <p>i am using this binary search algorithm to find items in my array. I am trying to make it so when i search for a value which doesn't appear in the array my program tells me, and it also reveals where the closest items are </p>
  
  <p>Example Array: (4, 6, 7, 8, 9)
  Search for 5
  Result 6, 7.</p>
  
  <p>Every time i search for something which isn't an element within my array it returns 0, or -1. Can someone help me out, thanks?</p>
  
  <pre><code>  public static double BinarySearch(double[] a, double item)
      {
          int first = 0;
          int last = a.Length - 1;
          do
          {
              int mid = first + (last - first) / 2;
              if (item &gt; a[mid])
                  first = mid + 1;
              else
                  last = mid - 1;
              if (a[mid] == item)
                  return mid;
          } while (first &lt;= last);       
          return -1;
      }
  </code></pre>