-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearch.java
More file actions
29 lines (28 loc) · 789 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
29 lines (28 loc) · 789 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
public class BinarySearch {
public static boolean binarySearch(int arr[],int k){
int left = 0;
int right = arr.length-1;
int mid;
while (left<=right){
mid = (right + left) / 2;
if(arr[mid] > k){
right = mid-1;
}
else if(arr[mid] < k){
left = mid+1;
}
else{
return true;
}
}
return false;
}
public static void main(String[] args) {
int arr[] = {1, 4, 6, 7, 10, 15, 18, 20};
// The given array must be sorted before performing a binary search.
if (binarySearch(arr, 7))
System.out.print("Exist");
else
System.out.print("Not Exist");
}
}