From 894d9d1b65ecc31b5e97a263ff2ed0bc86789b8e Mon Sep 17 00:00:00 2001 From: DivjotBatra <86954038+DivjotBatra@users.noreply.github.com> Date: Mon, 10 Oct 2022 23:10:03 +0530 Subject: [PATCH] Create binarysearch197.java --- binarysearch197.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 binarysearch197.java diff --git a/binarysearch197.java b/binarysearch197.java new file mode 100644 index 0000000..6e4dcbf --- /dev/null +++ b/binarysearch197.java @@ -0,0 +1,32 @@ +// recursive Binary Search Java +class BinarySearch { + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) { + int mid = l + (r - l) / 2; + if (arr[mid] == x) + return mid; + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + return binarySearch(arr, mid + 1, r, x); + } + + // when element is not present in array + return -1; + } + + // Driver Code + public static void main(String args[]) + { + BinarySearch ob = new BinarySearch(); + int arr[] = { 2, 3, 4, 10, 40 }; + int n = arr.length; + int x = 10; + int result = ob.binarySearch(arr, 0, n - 1, x); + if (result == -1) + System.out.println("Element not present"); + else + System.out.println("Element found at index " + + result); + } +}