-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathBinarySearch.java
More file actions
48 lines (39 loc) · 1008 Bytes
/
BinarySearch.java
File metadata and controls
48 lines (39 loc) · 1008 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
39
40
41
42
43
44
45
46
47
48
import java.util.Scanner;
class BinarySearch{
public static int[] input()
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n];
for(int x=0 ; x<a.length ; x++)
{
a[x] = sc.nextInt();
}
return a;
}
public static int binarySearch(int[] a, int x)
{
int start = 0, end = a.length-1;
while(start<=end){
int mid = (start+end)/2;
if(a[mid] == x)
return mid;
else if(x>a[mid])
start = mid+1;
else
end = mid-1;
}
return -1;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int a[] = input();
int t = sc.nextInt();
for(int x=1 ; x<=t ; x++)
{
int n = sc.nextInt();
System.out.println(binarySearch(a,n));
}
}
}