-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.java
More file actions
58 lines (41 loc) · 1.32 KB
/
binarysearch.java
File metadata and controls
58 lines (41 loc) · 1.32 KB
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
50
51
52
53
54
55
56
57
58
import java.util.Scanner;
public class binarysearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s= new Scanner(System.in);
int i,n;
System.out.println("Enter the number of elements");
n= s.nextInt();
int a[]= new int[n];
System.out.println("Enter the numbers:");
for(i=0;i<n;i++)
{
a[i]= s.nextInt();
}
// Enter the element which you want to search
System.out.println("Enter the element to be searched");
int searchnumber= s.nextInt();
int low=0;
int high= n-1;
int middle= low+high/2;
while(low<=high)
{
if(a[middle]< searchnumber)
{
low= middle+1;
}
else if(a[middle]== searchnumber)
{
System.out.println("Search number is located at" + (middle+1));
break;
}
else
high=middle-1;
middle= low+high/2;
}
if(low>high)
{
System.out.println("Wrong number have been searched");
}
}
}