title: Sorting and Binary search using Java
body: <p>I was asked to sort and search an array. The sorting the array was simple and my code worked but then whenever I try to call the binary search method it works for the first element in the array but gives me "-1" as a result</p>
  
  <p>My full code is as follows:</p>
  
  <pre><code> public static void main(String[] args) {
  
      int[] array = new int[5];
      array[0] = 50;
      array[1] = 40;
      array[2] = 10;
      array[3] = 20;
      array[4] = 100;
  
  sort(array, (array.length - 1));
  
        for (int x = 0; x &lt; array.length; x++) {
          System.out.println(" " + array[x]);
      }
      System.out.println("");
      System.out.println("Binary search (R): " + rBsearch(array, 0, (array.length), 20));
  }
      public static void sort(int[] a, int last) {
      if (last &gt; 0) {
          int max = findMax(a, last);
          swap(a, last, max);
          sort(a, last - 1);
      }
  }
  
  public static int rBsearch(int[] L, int low, int high, int k) {
  
  
      int mid = (low + high) / 2;
  
      if (low &gt; high) {
          return -1;
      } else if (L[mid] == k) {
          return mid;
      } else if (L[mid] &lt; k) {
          return rBsearch(L, k, mid + 1, high);
      } else {
          return rBsearch(L, k, low, mid - 1);
      }
   }
  
  public static int findMax(int[] arr, int last) {
  
      int max = 0;
      for (int i = 0; i &lt;= last; i++) {
          if (arr[i] &gt; arr[max]) {
              max = i;
          }
      }
      return max;
      }
  
  public static void swap(int[] arr, int last, int max) {
      int temp = arr[last];
      arr[last] = arr[max];
      arr[max] = temp;
  }
  </code></pre>