| 1 | // Java implementation of recursive Binary Search |
| 2 | class BinarySearch { |
| 3 | // Returns index of x if it is present in arr[l.. |
| 4 | // r], else return -1 |
| 5 | int binarySearch(int arr[], int l, int r, int x) |
| 6 | { |
| 7 | if (r >= l) { |
| 8 | int mid = l + (r - l) / 2; |
| 9 | |
| 10 | // If the element is present at the |
| 11 | // middle itself |
| 12 | if (arr[mid] == x) |
| 13 | return mid; |
| 14 | |
| 15 | // If element is smaller than mid, then |
| 16 | // it can only be present in left subarray |
| 17 | if (arr[mid] > x) |
| 18 | return binarySearch(arr, l, mid - 1, x); |
| 19 | |
| 20 | // Else the element can only be present |
| 21 | // in right subarray |
| 22 | return binarySearch(arr, mid + 1, r, x); |
| 23 | } |
| 24 | |
| 25 | // We reach here when element is not present |
| 26 | // in array |
| 27 | return -1; |
| 28 | } |
| 29 | |
| 30 | // Driver method to test above |
| 31 | public static void main(String args[]) |
| 32 | { |
| 33 | BinarySearch ob = new BinarySearch(); |
| 34 | int arr[] = { 2, 3, 4, 10, 40 }; |
| 35 | int n = arr.length; |
| 36 | int x = 10; |
| 37 | int result = ob.binarySearch(arr, 0, n - 1, x); |
| 38 | if (result == -1) |
| 39 | System.out.println("Element not present"); |
| 40 | else |
| 41 | System.out.println("Element found at index " + result); |
| 42 | } |
| 43 | } |
nothing calls this directly
no outgoing calls
no test coverage detected