-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq4.java
More file actions
39 lines (27 loc) · 1.04 KB
/
q4.java
File metadata and controls
39 lines (27 loc) · 1.04 KB
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
public class q4{
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; // Avoids overflow
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Target not found
}
public static void main(String[] args) {
int[] sortedNumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 7;
int result = binarySearch(sortedNumbers, target);
if (result != -1) {
System.out.println("Element " + target + " found at index: " + result);
} else {
System.out.println("Element " + target + " not found in the array");
}
}
}