-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathbinary search.java
More file actions
47 lines (43 loc) · 906 Bytes
/
binary search.java
File metadata and controls
47 lines (43 loc) · 906 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
import java.util.*;
class binarysearch
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
binarysearch bs = new binarysearch();
System.out.print("Enter the size:");
int n=sc.nextInt();
int[] A = new int[n];
System.out.print("Enter the elements:");
for(int i=0;i<n;i++)
A[i] = sc.nextInt();
System.out.print("Enter the item to be searched:");
int item = sc.nextInt();
int k = bs.Binaryser(A,n,item);
if(k!=0)
System.out.println(item+" is found at position "+k);
else
System.out.println("Element "+item+" not in the list");
}
int Binaryser(int A[], int n, int item)
{
int beg=0,end=n-1,mid;
while(beg<=end)
{
mid=(beg+end)/2;
if(A[mid]==item)
{
return(mid+1);
}
else if(item>A[mid])
{
beg=mid+1;
}
else
{
end=mid-1;
}
}
return 0;
}
}