-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchAlgo
More file actions
39 lines (29 loc) · 841 Bytes
/
BinarySearchAlgo
File metadata and controls
39 lines (29 loc) · 841 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
34
35
36
37
38
public class BinarySearchingAlgo {
public static void main(String args[]) {
int arr[]= {2,6,7,10,13,15,17,23,34,45,54};
BinarySearchingAlgo binarySearch=new BinarySearchingAlgo();
int find=binarySearch.search(arr,60);
if(find==-1) {
System.out.println("key not find");
}else {
System.out.println("key find at index "+find );
}
}
int search(int arr[],int keyIndex) {
int l = 0, r = arr.length - 1;
while (l <= r)
{
int m = (r+l)/2;
// Check if x is present at mid
if (arr[m] == keyIndex)
return m;
// If x greater, ignore left half
if (arr[m] < keyIndex)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
return -1;
}
}