Recursive Binary Search Implementation in Java

 
public class Main {
  public static final int NOT_FOUND = -1;
  public static int binarySearch(Comparable[] a, Comparable x) {
    return binarySearch(a, x, 0, a.length - 1);
  }

  private static int binarySearch(Comparable[] a, Comparable x, int low, int high) {
    if (low > high)
      return NOT_FOUND;

    int mid = (low + high) / 2;

    if (a[mid].compareTo(x) < 0)
      return binarySearch(a, x, mid + 1, high);
    else if (a[mid].compareTo(x) > 0)
      return binarySearch(a, x, low, mid - 1);
    else
      return mid;
  }

  public static void main(String[] args) {
    int SIZE = 8;
    Comparable[] a = new Integer[SIZE];
    for (int i = 0; i < SIZE; i++)
      a[i] = new Integer(i * 2);

    for (int i = 0; i < SIZE * 2; i++)
      System.out.println("Found " + i + " at " + binarySearch(a, new Integer(i)));
  }
}
  
Home 
  Java Book 
    Runnable examples  

Algorithm:
  1. Binary search
  2. Binary Search Insert
  3. Recursive Binary Search Implementation in Java
  4. Linear Searching double Arrays
  5. Bubble sort
  6. Heap sort
  7. Merge sort
  8. Fast Merge Sort
  9. Fast Quick Sort
  10. Simple version of quick sort
  11. Quicksort for sorting arrays
  12. Quick Sort Implementation with median-of-three partitioning and cutoff for small arrays
  13. Quick sort with median-of-three partitioning
  14. Insert sort
  15. Insert Sort for objects
  16. Selection sort
  17. Shell sort
  18. Fibonacci
  19. Hanoi puzzle
  20. Table of fahrenheit and celsius temperatures
  21. Growable integer array
  22. Linked List class
  23. Binary Tree
  24. Tree with generic user object