/** * BinarySearchR.java *
* A class to demonstrated recursive binary search on a sorted array. *
* Created: Tue Feb 11 14:30:59 2003 * * @author Stuart C. Shapiro */ public class BinarySearchR { /** * Returns the index within the array a of the first occurrence of the int i, * or -1 if i does not occur in a. *

The search range is a[min .. max].

* a is assumed to be sorted from lower to higher ints. * * @param a the sorted int[] to be searched. * @param min is the smallest index of a where x might be. * @param max is largest index of a where x might be. * @param i an int value to search for. * @return the index of the first occurrence of i in a, * or -1 if i does not occur in a. */ public static int indexOf(int[] a, int min, int max, int i) { if (min > max) return -1; int mid = (min + max) / 2; if (i == a[mid]) return mid; else if (i < a[mid]) return indexOf(a, min, mid-1, i); else return indexOf(a, mid+1, max, i); } /** * Tests the indexOf method. * */ private static void test(int[] a, int lo, int hi, int i) { System.out.print(i + " is at position " + indexOf(a, lo, hi, i) + " of " + "\t{" + a[0]); for (int j = 1; j < a.length; j++) {System.out.print(", " + a[j]);} System.out.println("}"); } /** * Demonstrates recursive binary search. * * @param args a String[] value */ public static void main (String[] args) { int[] testarray = {2,4,25,43,43,46,54,54,85,285,541,564}; test(testarray, 0, testarray.length-1, 54); test(testarray, 0, testarray.length-1, 1); test(testarray, 0, testarray.length-1, 99); test(testarray, 0, testarray.length-1, 999); } // end of main () }// BinarySearchR