-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
26 lines (25 loc) · 830 Bytes
/
BinarySearch.java
File metadata and controls
26 lines (25 loc) · 830 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
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50, 60, 70};
int index = binarySearch(arr, 8);
if(index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
public static int binarySearch(int[] arr, int key) {
int low = 0, high = arr.length - 1;
while(low <= high) {
int mid = low+high/ 2;
if(arr[mid]==key) {
return mid;
} else if(arr[mid]<key) {
low=mid+1;
} else{
high=mid-1;
}
}
return -1;
}
}