title: Why does this binary search implementation cause stack overflow in Ruby but not Java?
body: <h1>Ruby</h1>
  <pre><code>def binary_search(arr, l, r, x) 
    if r &gt;= 1 then
      mid = l + (r - 1) / 2
  
      if arr[mid] == x then
        return mid
      end
  
      if arr[mid] &gt; x then
        return binary_search(arr, l, mid - 1, x)
      end
      return binary_search(arr, mid + 1, r, x)
    end
  
    return -1
  end
  </code></pre>
  <h1>Java</h1>
  <pre><code>int binarySearch(int arr[], int l, int r, int x) 
  { 
      if (r &gt;= l) { 
          int mid = l + (r - l) / 2; 
  
          // If the element is present at the 
          // middle itself 
          if (arr[mid] == x) 
              return mid; 
  
          // If element is smaller than mid, then 
          // it can only be present in left subarray 
          if (arr[mid] &gt; x) 
              return binarySearch(arr, l, mid - 1, x); 
  
          // Else the element can only be present 
          // in right subarray 
          return binarySearch(arr, mid + 1, r, x); 
      } 
  
      // We reach here when element is not present 
      // in array 
      return -1; 
  } 
  </code></pre>
  <p>When x (the target element) is in the right half of a sorted array, a stack overflow occurs and I get this error in Ruby</p>
  <pre><code>SystemStackError (stack level too deep)
  </code></pre>
  <p>why does this happen in ruby and not in java? I'm running the program in irb. the java implementation came straight from here <a href="https://www.geeksforgeeks.org/binary-search/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/binary-search/</a>  .</p>