Skip to content

Commit 4c83f01

Browse files
committed
Added Solution for Binary Search in Java (issue #5529)
1 parent 7b934af commit 4c83f01

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.thealgorithms.searches;
2+
3+
class BinarySearch {
4+
5+
// Enhanced binary search method
6+
public static int binarySearch(int[] arr, int target) {
7+
// Edge case: If the array is empty
8+
if (arr == null || arr.length == 0) {
9+
System.out.println("Array is empty or null.");
10+
return -1;
11+
}
12+
13+
int left = 0;
14+
int right = arr.length - 1;
15+
16+
while (left <= right) {
17+
// Prevent overflow for large values by calculating mid this way
18+
int mid = left + (right - left) / 2;
19+
20+
// Debugging statement for tracking the mid element
21+
System.out.println("Mid index: " + mid + ", Mid element: " + arr[mid]);
22+
23+
if (arr[mid] == target) {
24+
return mid; // Target found at index 'mid'
25+
} else if (arr[mid] < target) {
26+
left = mid + 1; // Search in the right half
27+
} else {
28+
right = mid - 1; // Search in the left half
29+
}
30+
}
31+
32+
// If the target is not found
33+
System.out.println("Target not found.");
34+
return -1;
35+
}
36+
37+
public static void main(String[] args) {
38+
int[] arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19}; // Sample sorted array
39+
int target = 7;
40+
41+
int result = binarySearch(arr, target);
42+
43+
if (result != -1) {
44+
System.out.println("Target " + target + " found at index: " + result);
45+
} else {
46+
System.out.println("Target " + target + " not found in the array.");
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)