forked from iRupam/NewtonSchoolInfinityJune21
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
32 lines (29 loc) · 819 Bytes
/
BinarySearch.java
File metadata and controls
32 lines (29 loc) · 819 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
31
32
package InfinityJune21.SearchTechniques;
public class BinarySearch {
public static void main(String[] args) {
int arr[] = {18, 19, 21, 25, 40, 88, 115};
int length = arr.length;
int key = 125;
int left = 0;
int right = length - 1;
int mid = -1;
while(left <= right) {
mid = (left + right) / 2;
if(arr[mid] > key) {
right = mid - 1;
}
else if(arr[mid] < key) {
left = mid + 1;
}
else {
break;
}
}
if(left > right) {
System.out.println("Element not found");
}
else {
System.out.println("Element found at index " + mid);
}
}
}