|
| 1 | +package com.codefortomorrow.advanced.chapter13.examples; |
| 2 | + |
| 3 | +public class BinarySearch { |
| 4 | + // Java implementation of recursive Binary Search |
| 5 | + // Returns index of x if it is present in arr[l.. |
| 6 | + // r], else return -1 |
| 7 | + public static int binarySearch(int arr[], int l, int r, int x) |
| 8 | + { |
| 9 | + if (r >= l) { |
| 10 | + int mid = l + (r - l) / 2; |
| 11 | + |
| 12 | + // If the element is present at the |
| 13 | + // middle itself |
| 14 | + if (arr[mid] == x) |
| 15 | + return mid; |
| 16 | + |
| 17 | + // If element is smaller than mid, then |
| 18 | + // it can only be present in left subarray |
| 19 | + if (arr[mid] > x) |
| 20 | + return binarySearch(arr, l, mid - 1, x); |
| 21 | + |
| 22 | + // Else the element can only be present |
| 23 | + // in right subarray |
| 24 | + return binarySearch(arr, mid + 1, r, x); |
| 25 | + } |
| 26 | + |
| 27 | + // We reach here when element is not present |
| 28 | + // in array |
| 29 | + return -1; |
| 30 | + } |
| 31 | + |
| 32 | + // Driver method to test above |
| 33 | + public static void main(String args[]) |
| 34 | + { |
| 35 | + int arr[] = { 2, 3, 4, 10, 40 }; |
| 36 | + int n = arr.length; |
| 37 | + int x = 10; |
| 38 | + int result = binarySearch(arr, 0, n - 1, x); |
| 39 | + if (result == -1) |
| 40 | + System.out.println("Element not present"); |
| 41 | + else |
| 42 | + System.out.println("Element found at index " + result); |
| 43 | + } |
| 44 | + /* This code is contributed by Rajat Mishra |
| 45 | + https://www.geeksforgeeks.org/binary-search/ */ |
| 46 | + |
| 47 | +} |
0 commit comments