|
| 1 | +package com.thealgorithms.searches; |
| 2 | + |
| 3 | +import java.util.Scanner; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author: Lahu Shahadev Andhale |
| 7 | + * @date: 1-10-2023(Sunday) |
| 8 | + */ |
| 9 | +/* |
| 10 | + * Recursive Binary Search is an efficient algorithm for finding a search |
| 11 | + * element within a sorted array of data. It works by repeatedly dividing the |
| 12 | + * search |
| 13 | + * space in half until the desired element is found or it is determined that the |
| 14 | + * element |
| 15 | + * is not present in the array. |
| 16 | + */ |
| 17 | +public class RecursiveBinarySearch { |
| 18 | + |
| 19 | + public static int BinarySearchRecursively(int n, int arr[], int search, int firstIdx, int lastIdx) { |
| 20 | + if (lastIdx >= firstIdx) { |
| 21 | + //We are finding mid; |
| 22 | + int mid = (firstIdx + lastIdx) / 2; |
| 23 | + //Checking is value at mid is equal to the search ; |
| 24 | + if (arr[mid] == search) { |
| 25 | + return mid; |
| 26 | + } else if (arr[mid] > search) { |
| 27 | + //recursively call the binary search on the left half of the array |
| 28 | + return BinarySearchRecursively(n, arr, search, firstIdx, mid - 1); |
| 29 | + } else { |
| 30 | + //recursively call the binary search on the right half of the array |
| 31 | + return BinarySearchRecursively(n, arr, search, mid + 1, lastIdx); |
| 32 | + } |
| 33 | + } |
| 34 | + return -1; |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String args[]) { |
| 38 | + Scanner sc = new Scanner(System.in); |
| 39 | + System.out.print("Enter the size of data set: "); |
| 40 | + int n = sc.nextInt(); |
| 41 | + int arr[] = new int[n]; |
| 42 | + System.out.print("Enter the elements in sorted order: "); |
| 43 | + for (int i = 0; i < n; i++) { |
| 44 | + arr[i] = sc.nextInt(); |
| 45 | + } |
| 46 | + System.out.print("Enter the element to be search over data set: "); |
| 47 | + int search = sc.nextInt(); |
| 48 | + int idx = BinarySearchRecursively(n, arr, search, 0, n - 1); |
| 49 | + if (idx == -1) { |
| 50 | + System.out.println("Element is not present in the given data set"); |
| 51 | + } else { |
| 52 | + System.out.println("The element is present at the index: " + idx + " value is " + arr[idx]); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
| 56 | +/* input and Output: |
| 57 | + * Enter the size of data set: 10 |
| 58 | + * Enter the elements in sorted order: 2 4 5 6 7 8 9 10 22 24 |
| 59 | + * Enter the element to be search over data set: 22 |
| 60 | + * The element is present at the index: 8 value is 22 |
| 61 | + */ |
| 62 | +/* |
| 63 | + * Complexity Analysis: |
| 64 | + * Best Case: O(1) the element is found at mid int first iteration |
| 65 | + * Average Case: T(N)=T(N/2)+c that is " O(log N) " |
| 66 | + * Worst Case: T(N)=T(N/2)+c that is " O(log N) " |
| 67 | + * Space Complexity: O(logN) that is size of recursion tree. |
| 68 | + */ |
0 commit comments