/* * Return the index of element x within array A if present, * and return -1 if not found */ static public int BinarySearch (int [] A, int x, int size) { return BoundedBinarySearch(A, x, 0, size-1); } /* * Return the index of element x within A[left...right] if present, * and return -1 if not found */ static public int BoundedBinarySearch (int [] A, int x, int left, int right) { if (left > right) { /* base case: zero size */ return -1; } if (left == right) { /* base case: size one */ if (A[left] == x) return left; else return -1; } int mid = (left + right) / 2; if (A[mid] == x) { return mid; } else if (A[mid] > x) { /* look in left half */ return BoundedBinarySearch (A, x, left, mid-1); } else { /* A[mid] < x --- recurse on right half */ return BoundedBinarySearch (A, x, mid+1, right); } } /* Editor's note: the size one base case is not necessary */ /* It is worth your while to verify that it's ok to drop it. */