From 574c4b32a3c673cb12910ecd74b044cf58140ced Mon Sep 17 00:00:00 2001 From: Amisha-Mohapatra <68538660+Amisha-Mohapatra@users.noreply.github.com> Date: Fri, 22 Jan 2021 01:45:29 -0500 Subject: [PATCH] Add binary-search java program --- searching/c-or-cpp/stderr.txt | 0 searching/c-or-cpp/stdout.txt | 0 searching/java/binary-search.txt | 47 ++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 searching/c-or-cpp/stderr.txt create mode 100644 searching/c-or-cpp/stdout.txt create mode 100644 searching/java/binary-search.txt diff --git a/searching/c-or-cpp/stderr.txt b/searching/c-or-cpp/stderr.txt new file mode 100644 index 00000000..e69de29b diff --git a/searching/c-or-cpp/stdout.txt b/searching/c-or-cpp/stdout.txt new file mode 100644 index 00000000..e69de29b diff --git a/searching/java/binary-search.txt b/searching/java/binary-search.txt new file mode 100644 index 00000000..519448af --- /dev/null +++ b/searching/java/binary-search.txt @@ -0,0 +1,47 @@ +// Java implementation of recursive Binary Search +class BinarySearch { + // Returns index of x if it is present in arr[l..r], + // else return -1 + int binarySearch(int arr[], int l, int r, int x) + { + if (r >= l) { + int mid = l + (r - l) / 2; + + // If the element is present at the + // middle itself + if (arr[mid] == x) + return mid; + + // If element is smaller than mid, then + // it can only be present in left subarray + if (arr[mid] > x) + return binarySearch(arr, l, mid - 1, x); + + // Else the element can only be present + // in right subarray + return binarySearch(arr, mid + 1, r, x); + } + + // We reach here when element is not present + // in array + return -1; + } + + // Driver method to test above + 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); + } +} + +// For running in terminal rename this file to BinarySearch.java +//then run the commands followed by +//It will generate and a BinarySearch.class file which is a file containing java bytecode that is executed by JVM.