title: Java Leftmost Binary Search
body: <p>I am trying to modify a Recursive Binary Search function so that it will find the leftmost index of the element given the array contains multiples of that element.</p>
  
  <pre><code>import java.util.*;
  import java.util.Arrays;
  import java.io.File;
  import java.io.IOException;
  
  public class LeftmostBinarySearch {
  
      private static int myBinarySearch(int key, int[] a, int lo, int hi) {
      if (lo &gt; hi) {
          return -1;
      }
      int mid = lo + (hi - lo) / 2;
      if (key &lt; a[mid]) {
          return myBinarySearch(key, a, lo, mid - 1);
      } else if (key &gt; a[mid]) {
          return myBinarySearch(key, a, mid + 1, hi);
      } else {
          return mid;
      }
  }
  
      public static int myBinarySearch(int key, int[] a) {
      return myBinarySearch(key, a, 0, a.length - 1);
  }
  
      public static void main(String[] args) throws IOException {
          String fileName = args[0] + ".txt";
          System.out.println(fileName);
          Scanner scanner = new Scanner(new File(fileName));
          int[] data = new int[7];
          int i = 0;
          int j = 0;
  
          while (scanner.hasNextInt()) {
              data[i] = scanner.nextInt();
              i++;
          }
          Arrays.sort(data);
          System.out.format("%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s", " 0",
                  "  ", " 1", "  ", " 2", "  ", " 3", "  ", " 4", "  ", " 5", "  ", " 6\n");
          System.out.format("%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s%2s", data[j],
                  "  ", data[j + 1], "  ", data[j + 2], "  ", data[j + 3], "  ",
                  data[j + 4], " ", data[j + 5], "  ", data[j + 6] + "\n");
  
          int input = new Scanner(System.in).nextInt();
  
          while ((Integer) input != null) {
              int key = input;
              System.out.println(data[0]);
              if (myBinarySearch(key, data) != -1) {
                  System.out.println(input + " found: "
                          + myBinarySearch(key, data));
              }
              input = new Scanner(System.in).nextInt();
          }
      }
  }
  </code></pre>
  
  <p>The output I have gotten from this is:</p>
  
  <pre><code>C:\Users\Shirley\algs4&gt;java LeftmostBinarySearch mydata
   0   1   2   3   4   5   6
  10  20  20  30  40  40  40
  10
  10 found: 0
  20
  20 found: 1
  30
  30 found: 3
  40
  40 found: 5
  </code></pre>
  
  <p>I have tried changing how I calculate mid to (hi + lo - 1)/2 and it works for 40, gives index 3, but for 20 it gives index 2.</p>