- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearchExample.java
More file actions
Latest commit
33 lines (29 loc) · 854 Bytes
/
Copy pathBinarySearchExample.java
File metadata and controls
33 lines (29 loc) · 854 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
33
packagecom.codinginterview;
publicclassBinarySearchExample {
publicstaticvoidmain(String[] args) {
System.out.println("Binary Search Example!");
int[] arr = {1,2,4,6,7,12,13,14};
intkey = 12;
intlow = 0;
inthigh = arr.length;
System.out.println("Index of Key is :: "+
binarySearch(arr, low, high, key));
}
privatestaticintbinarySearch(intarr[], intlow, inthigh, intkey){
intmid = (low + high)/2;
while(low <= high){
if(arr[low] < key) {
low = mid + 1;
}elseif (arr[mid] == key){
returnmid;
}else{
high = mid - 1;
}
mid = (low + high)/2;
}
if(low > high){
return -1;
}
return -1;
}
}