title: Binary Search to find greatest element less than or equal to another element
body: <p>I am striving for a binary search function that given a element in a vector, searches for the element that is closest to that element but still less than or equal to it. However my code is resulting in garbage numbers. Here is my code:</p>
  
  <pre><code>int close(vector&lt;int&gt; r, vector&lt;int&gt; g, int pos){
      int lastpos = 0;
      int mid = int((r.size())/2);
      while(mid&gt;=1){
          if(r[lastpos+mid]&gt;g[pos]){}
          else{
              lastpos += mid;
              if(r[lastpos+1]&gt;g[pos] || r[lastpos]==r[r.size()-1]){
                  return r[lastpos];
              }
          }
          mid/=2;
      }
      return r[0];
  }
  </code></pre>
  
  <hr>
  
  <p>For example, if I call the function with (r, g, 1) and it is given that g[1]=3 and vector r contains {1, 3, 4}, this function will set mid to 3/2 but round it down to an integer, so one. The last position(lastpos) is defaultly set to 0. Now, my function will check if r[lastpos + mid] > g[pos] or if 3 > 3. It is not because they are equal. Now my function will continue to the else condition, and add mid to lastpos. Now lastpos = 1. Now, it'll check if r[lastpos+1]>g[pos] to see if this is the minimal value that is closest and less than or equal to g[1]. Since the next element is 4 and 4 is greater than 3 it'll return 3.</p>
  
  <p>However if lastpos is the end element, then it'll simply return the end element, because there are no more numbers to check. </p>
  
  <p><strong>Exceptions</strong>: If there is no such element in vector r that is less than or equal to an element in vector g it'll return the first element in vector r. </p>
  
  <p><strong>Note</strong>: These vectors are sorted</p>