|
| 1 | +public class BinarySearch { |
| 2 | + |
| 3 | + /** |
| 4 | + * Searches an element {@param n} in a sorted array {@param a} |
| 5 | + * and returns its index in O(log n) time. The Index may not |
| 6 | + * correspond to the first occurrence of the element. |
| 7 | + * |
| 8 | + * @param a sorted array to be searched |
| 9 | + * @param n number to be searched in the array |
| 10 | + * @return index of {@param n} or {@code -1} if not present |
| 11 | + */ |
| 12 | + public static int binarySearch(int[] a, int n) { |
| 13 | + return binarySearch(a, n, 0, a.length - 1); |
| 14 | + } |
| 15 | + |
| 16 | + public static int binarySearch(int[] a, int n, int low, int high) { |
| 17 | + |
| 18 | + if (low <= high) { |
| 19 | + int mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2 |
| 20 | + |
| 21 | + if (n == a[mid]) { |
| 22 | + return mid; |
| 23 | + } else if (n < a[mid]) { |
| 24 | + return binarySearch(a, n, 0, mid - 1); |
| 25 | + } else { |
| 26 | + return binarySearch(a, n, mid + 1, high); |
| 27 | + } |
| 28 | + } else { |
| 29 | + return -1; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Non-recursive version of binary search. |
| 35 | + * |
| 36 | + * @param a sorted array to be searched |
| 37 | + * @param n number to be searched in the array |
| 38 | + * @return index of {@param n} or {@code -1} if not present |
| 39 | + */ |
| 40 | + public static int binarySearchNonRecursive(int[] a, int n) { |
| 41 | + int low = 0, high = a.length, mid; |
| 42 | + while (low <= high) { |
| 43 | + mid = (low + high) / 2; // to prevent overflow you can instead do: mid = low + (high - low) / 2 |
| 44 | + if (n == a[mid]) { |
| 45 | + return mid; |
| 46 | + } else if (n < a[mid]) { |
| 47 | + high = mid - 1; |
| 48 | + } else { |
| 49 | + low = mid + 1; |
| 50 | + } |
| 51 | + } |
| 52 | + return -1; |
| 53 | + } |
| 54 | + |
| 55 | + /** |
| 56 | + * Driver for testing. |
| 57 | + * |
| 58 | + * @param a |
| 59 | + */ |
| 60 | + public static void main(String[] args) { |
| 61 | + System.out.println(binarySearch(new int[]{0, 2}, 2)); |
| 62 | + System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 2)); |
| 63 | + System.out.println(binarySearch(new int[]{0, 1, 2, 3}, 3)); |
| 64 | + System.out.println(binarySearch(new int[]{0, 2}, 0)); |
| 65 | + System.out.println(binarySearch(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); // doesn't return index of first occurrence |
| 66 | + System.out.println("---------"); |
| 67 | + System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 2)); |
| 68 | + System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 2)); |
| 69 | + System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 3}, 3)); |
| 70 | + System.out.println(binarySearchNonRecursive(new int[]{0, 2}, 0)); |
| 71 | + System.out.println(binarySearchNonRecursive(new int[]{0, 1, 2, 2, 2, 3, 3}, 2)); |
| 72 | + } |
| 73 | +} |
0 commit comments