title: How to get the last char in an array with a binary search
body: <p>My teacher wrote an algorithm to find a number in an array. I have tried to convert it to find a <code>char</code>.</p>
  
  <p>If I search for the the first <code>char</code> of an array it works, but if I try to find the last <code>char</code> in the same array it gives me 0 or an unexpected number (like 100+, when the array is like 4 <code>char</code>s).</p>
  
  <p>Here's the code:</p>
  
  <pre><code>int myIndex = binarySearch(sentence , word[0], 0, sentence.length -1);
  
  char [] sentence = {'s','t','a','c','k','o','v','e','r','f','l','o','w'};
  char [] word = {'o','v','e','r'};
  
  static int binarySearch(char [] arr, char x, int l, int r){
      if(r&lt;l){
          return 0;
      }
  
      int m = l+(r-l)/2;
      if(arr[m] == x){
          return m;
      }
      if(arr[m] &lt; x){
          return binarySearch(arr, x, m+1, r);
      }
      return binarySearch(arr, x, l, m-1);
  }
  </code></pre>
  
  <p>If I search for the first letter in the <code>word</code> array it works fine, but if I search for the last letter in the <code>word</code> array it breaks.</p>