-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinarySearch.java
More file actions
49 lines (41 loc) · 774 Bytes
/
binarySearch.java
File metadata and controls
49 lines (41 loc) · 774 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
49
import java.util.Scanner;
public class binarySearch {
public static int[] takeInput() {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int a[]=new int[n];
for (int i=0;i<n;i++){
a[i] = s.nextInt();
}
return a;
}
public static int binarySearch(int arr[], int num) {
int f = 0,index=0;
int l = arr.length - 1;
int m = (f+l)/2;
while (f <= l)
{
if (arr[m] < num)
f= m+1;
else if (arr[m] == num)
{
index= m;
break;
}
else{
l = m - 1;
m = (f+l)/2;
}
}
if (f > l){
index= -1;
}
return index;
}
public static void main(String[] args) {
int a[]=takeInput();
Scanner s = new Scanner(System.in);
int num = s.nextInt();
System.out.println(binarySearch(a,num));
}
}