Recursive Binary Search
This program performs binary search using recursion.
Problem Statement
Write a Java program to search for a given element in a sorted integer array using recursive binary search.
Source Code
| 1 | public class RecursiveBinarySearch { |
| 2 | public static int binarySearch(int[] arr, int low, int high, int key) { |
| 3 | if(low > high) return -1; |
| 4 | int mid = (low + high)/2; |
| 5 | if(arr[mid] == key) return mid; |
| 6 | else if(arr[mid] < key) return binarySearch(arr, mid+1, high, key); |
| 7 | else return binarySearch(arr, low, mid-1, key); |
| 8 | } |
| 9 | public static void main(String[] args) { |
| 10 | System.out.println("Eduinq Recursive Binary Search"); |
| 11 | int[] arr = {5,10,15,20,25,30}; |
| 12 | int key = 25; |
| 13 | int result = binarySearch(arr,0,arr.length-1,key); |
| 14 | if(result!=-1) System.out.println("Element found at index: "+result); |
| 15 | else System.out.println("Element not found"); |
| 16 | } |
| 17 | } |
Program Output
Eduinq Recursive Binary Search Element found at index: 4
Explanation
Recursive function divides array into halves. - Base case checks if low > high. - Mid element compared with key. - Recursive calls continue until element found or not. - Together demonstrates recursive binary search. Conclusion: Shows how binary search can be implemented recursively.