title: Binary search to find the range in which the number lies
body: <p>I have an array</p>
  
  <pre><code>Values array: 12 20 32 40 52
                ^  ^  ^  ^  ^
                0  1  2  3  4
  </code></pre>
  
  <p>on which I have to perform binary search to find the index of the range in which the number lies. For example:</p>
  
  <ol>
  <li>Given the number ->  19 (It lies between index 0 and 1), return 0</li>
  <li>Given the number ->  22 (It lies between index 1 and 2), return 1</li>
  <li>Given the number -> 40 (It lies between index 3 and 4), return 3</li>
  </ol>
  
  <p>I implemented the binary search in the following manner, and this comes to be correct for case 1, and 3 but incorrect if we search for case 2 or 52, 55 32, etc.</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  int findIndex(int values[], int number, unsigned first, unsigned last)
  {
      unsigned midPoint;
      while(first&lt;last)
      {
          unsigned midPoint = (first+last)/2;
          if (number &lt;= values[midPoint])
              last = midPoint -1;
          else if (number &gt; values[midPoint])
              first = midPoint + 1;
      }
      return midPoint;
  }
  
  
  int main()
  {
      int a[] = {12, 20, 32, 40, 52};
      unsigned i = findIndex(a, 55, 0, 4);
      cout &lt;&lt; i;
  }
  </code></pre>
  
  <p>Use of additional variables such as <code>bool found</code> is not allowed.</p>