-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
48 lines (35 loc) · 868 Bytes
/
BinarySearch.java
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;
// Name: Binary Search in Arrays.
public class BinarySearch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int [] a = new int [n];
int data;
for(int i =0; i<n; i++)
{
a[i]= scanner.nextInt();
}
data = scanner.nextInt();
int l=0;
int h =n-1;
while (l<=h)
{
int mid = (l + h) /2;
if(data<a[mid])
{
h = mid-1;
}
else if(data>a[mid])
{
l = mid+1;
}
else
{
System.out.println("Found at position: "+mid);
return;
}
}
System.out.println("Not Found");
}
}