-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
29 lines (26 loc) · 890 Bytes
/
BinarySearch.java
File metadata and controls
29 lines (26 loc) · 890 Bytes
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
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 4;
int position = -1;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == k) {
position = mid; // Update position if k is found
break; // Exit loop once k is found
} else if (arr[mid] < k) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// Print the position of k in the array
if (position != -1) {
System.out.println("Position of " + k + " in the array: " + position);
} else {
System.out.println(k + " is not present in the array.");
}
}
}