Skip to content

Commit f9e9f20

Browse files
author
Farheen Shabbir Shaikh
committed
Add recursive Binary Search algorithm in Java with comments
1 parent 9d54909 commit f9e9f20

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Search/BinarySearch.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* BinarySearch.java
3+
* This program implements recursive Binary Search on a sorted array.
4+
* Time Complexity: O(log n)
5+
*/
6+
7+
public class BinarySearch {
8+
9+
// Recursive method to perform binary search
10+
public static int binarySearch(int[] arr, int left, int right, int target) {
11+
if (left > right) {
12+
return -1; // Base case: element not found
13+
}
14+
15+
int mid = left + (right - left) / 2;
16+
17+
if (arr[mid] == target) {
18+
return mid; // Found the target
19+
} else if (target < arr[mid]) {
20+
return binarySearch(arr, left, mid - 1, target); // Search in the left half
21+
} else {
22+
return binarySearch(arr, mid + 1, right, target); // Search in the right half
23+
}
24+
}
25+
26+
public static void main(String[] args) {
27+
int[] arr = {3, 8, 15, 23, 42, 56};
28+
int target = 23;
29+
30+
int result = binarySearch(arr, 0, arr.length - 1, target);
31+
32+
if (result != -1) {
33+
System.out.println("Target " + target + " found at index: " + result);
34+
} else {
35+
System.out.println("Target " + target + " not found in the array.");
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)