forked from ghostmkg/programming-language
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
40 lines (34 loc) · 1.11 KB
/
BinarySearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class BinarySearch {
// Method to perform binary search iteratively
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // To avoid overflow
// Check if target is present at mid
if (arr[mid] == target) {
return mid;
}
// If target is greater, ignore the left half
else if (arr[mid] < target) {
left = mid + 1;
}
// If target is smaller, ignore the right half
else {
right = mid - 1;
}
}
// Target was not found in the array
return -1;
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 40};
int target = 10;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not present in array");
} else {
System.out.println("Element found at index " + result);
}
}
}