From cd153f9912fc726d885633504791034913afe63a Mon Sep 17 00:00:00 2001 From: YashiSrivastava1 <75679042+YashiSrivastava1@users.noreply.github.com> Date: Mon, 17 Oct 2022 19:12:40 +0530 Subject: [PATCH] Create BinarySearch.java --- Java/BinarySearch.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Java/BinarySearch.java diff --git a/Java/BinarySearch.java b/Java/BinarySearch.java new file mode 100644 index 0000000..9d96df3 --- /dev/null +++ b/Java/BinarySearch.java @@ -0,0 +1,29 @@ +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); + } + return -1; + } + 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); + } +} +