forked from deepak-raaaz/web-dev-projects
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.java
More file actions
30 lines (27 loc) · 822 Bytes
/
Copy pathbinarysearch.java
File metadata and controls
30 lines (27 loc) · 822 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
30
public class BinarySearch {
public static int binarySearch(int[] array, int key) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == key) {
return mid;
} else if (array[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Key not found
}
public static void main(String[] args) {
int[] array = {2, 3, 4, 10, 40};
int key = 10;
int result = binarySearch(array, key);
if (result == -1) {
System.out.println("Element not found");
} else {
System.out.println("Element found at index: " + result);
}
}
}