title: Why is my code not running the function correctly
body: <p>The code need to find the max element in the 2d array that has the distance less than &lt;(square(d)). </p>
  
  <p>The 2d array is sorted from the the least distance to the max distance.</p>
  
  <p>The distance is calculated from a given point(x,y), for example:
  If we have a point(0,0) and 2d array(sorted) {{3,0},{3,-1},{3,3},{5,0},{7,2}}. and the d = (square(11)), then the max distance element point in array from (0,0) that less than d is {3,-1}, and the function needs to return (1) because it is the next element in  the array. </p>
  
  <p>Now the problem is the code outputting 3 instead of 1...!!!??  (note that I didn't use the function sqrt() in the code, instead I use d*d).</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #define X 0
  #define Y 0
  
  int square(int x);
  int diff(int a, int b);
  int find_distance(int points[][2], int n, int d);
  
  int diff(int a, int b){
    int dis=square(a-X)+square(b-Y);
  return dis;
  }
  
  int square(int x){
    return x*x;
  }
  
  int find_distance(int p[][2], int n, int d){
    int l=0, r=n-1, max=-1;
    while (l&lt;r){
      int mid=(l+r)/2;
      if(diff(p[mid][0], p[mid][1])&gt;= d*d)
          r=mid-1;
      else if (diff(p[mid][0],p[mid][1])&lt;d*d){
          if (max&lt;mid) 
              max=mid;
          l=mid+1;
      }
  
    }
    return max;
  }
  
  int main(){
    int p[5][2]={{3,0},{3,-1},{3,3},{5,0},{7,2}};
    int max=find_distance(p, 5, 11);
    printf("%d, %d", max, X);
  }
  </code></pre>