-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinarySearch.java
More file actions
34 lines (32 loc) · 817 Bytes
/
BinarySearch.java
File metadata and controls
34 lines (32 loc) · 817 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
import java.util.*;
class BinarySearch{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[] arr=new int[n];
for(int i=0;i<arr.length;i++){
arr[i]=in.nextInt();
}
int target=in.nextInt();
System.out.println(BS(arr,target));
in.close();
}
static int BS(int[] arr,int target){
int start,end;
start=0;
end=arr.length-1;
while(start<=end){
int mid=start+(end-start)/2;
if(arr[mid]==target){
return mid;
}
else if(target>arr[mid]){
start=mid+1;
}
else{
end=mid-1;
}
}
return -1;
}
}