-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbinarySearch.java
More file actions
44 lines (35 loc) · 781 Bytes
/
binarySearch.java
File metadata and controls
44 lines (35 loc) · 781 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
// binary search only works on sorted arrays
import java.util.*;
class binarySearch
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int[] arr=new int[5];
int beg,mid,end;
for(int i=0;i<=4;i++)
{
arr[i]=sc.nextInt();
}
int k=sc.nextInt();
beg=0;
end=arr.length-1;
while(beg<=end)
{
mid=(beg+end)/2;
if(arr[mid]==k)
{
System.out.println("Value found at: "+(mid+1));
break;
}
if(k>arr[mid])
{
beg=mid+1;
}
if(k<arr[mid])
{
end=mid-1;
}
}
}
}