|
| 1 | +// Code by Pronay Debnath |
| 2 | +// Created:- 1/10/2023 |
| 3 | +// File Name should be RecursiveBinarySearch.java |
| 4 | +// Explanation:- https://www.tutorialspoint.com/java-program-for-binary-search-recursive |
| 5 | + |
| 6 | +import java.util.*; |
| 7 | + |
| 8 | +// Create a SearchAlgorithm class with a generic type |
| 9 | +abstract class SearchAlgorithm<T extends Comparable<T>> { |
| 10 | + // Abstract find method to be implemented by subclasses |
| 11 | + public abstract int find(T[] arr, T target); |
| 12 | +} |
| 13 | + |
| 14 | +public class RecursiveBinarySearch<T extends Comparable<T>> extends SearchAlgorithm<T> { |
| 15 | + |
| 16 | + // Override the find method as required |
| 17 | + @Override |
| 18 | + public int find(T[] arr, T target) { |
| 19 | + // Call the recursive binary search function |
| 20 | + return binsear(arr, 0, arr.length - 1, target); |
| 21 | + } |
| 22 | + |
| 23 | + // Recursive binary search function |
| 24 | + public int binsear(T[] arr, int left, int right, T target) { |
| 25 | + if (right >= left) { |
| 26 | + int mid = left + (right - left) / 2; |
| 27 | + |
| 28 | + // Compare the element at the middle with the target |
| 29 | + int comparison = arr[mid].compareTo(target); |
| 30 | + |
| 31 | + // If the element is equal to the target, return its index |
| 32 | + if (comparison == 0) { |
| 33 | + return mid; |
| 34 | + } |
| 35 | + |
| 36 | + // If the element is greater than the target, search in the left subarray |
| 37 | + if (comparison > 0) { |
| 38 | + return binsear(arr, left, mid - 1, target); |
| 39 | + } |
| 40 | + |
| 41 | + // Otherwise, search in the right subarray |
| 42 | + return binsear(arr, mid + 1, right, target); |
| 43 | + } |
| 44 | + |
| 45 | + // Element is not present in the array |
| 46 | + return -1; |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) { |
| 50 | + Scanner sc = new Scanner(System.in); |
| 51 | + // User inputs |
| 52 | + System.out.print("Enter the number of elements in the array: "); |
| 53 | + int n = sc.nextInt(); |
| 54 | + |
| 55 | + Integer[] a = new Integer[n]; // You can change the array type as needed |
| 56 | + |
| 57 | + System.out.println("Enter the elements in sorted order:"); |
| 58 | + |
| 59 | + for (int i = 0; i < n; i++) { |
| 60 | + a[i] = sc.nextInt(); |
| 61 | + } |
| 62 | + |
| 63 | + System.out.print("Enter the target element to search for: "); |
| 64 | + int t = sc.nextInt(); |
| 65 | + |
| 66 | + RecursiveBinarySearch<Integer> searcher = new RecursiveBinarySearch<>(); |
| 67 | + int res = searcher.find(a, t); |
| 68 | + |
| 69 | + if (res == -1) |
| 70 | + System.out.println("Element not found in the array."); |
| 71 | + else |
| 72 | + System.out.println("Element found at index " + res); |
| 73 | + } |
| 74 | +} |
0 commit comments