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