-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
executable file
·74 lines (49 loc) · 1.14 KB
/
BinarySearch.java
File metadata and controls
executable file
·74 lines (49 loc) · 1.14 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.*;
class BinarySearch{
int[] arr;
int key;
public BinarySearch(){
arr=new int[100];
key=0;
}
int search(){
for(int i=0;i<this.arr.length;i++)
System.out.println(this.arr[i]);
int l,h,m;
l=0;
h=this.arr.length-1;
while(l<=h){
m=(l+h)/2;
if(key>this.arr[m])
l=m+1;
else if(this.arr[m]==this.key)
{
System.out.println(m);
return m;
}
else
h=m-1;
}
System.out.println("Element not found");
return -1;
}
public static void main(String[] args){
int n,res;
Scanner s = new Scanner(System.in);
BinarySearch bs = new BinarySearch();
System.out.println("Please enter the array lenght");
n=s.nextInt();
System.out.println("Please enter the sorted array elements");
for(int i=0;i<n;i++)
bs.arr[i]=s.nextInt();
System.out.println("Please enter the key you want to search");
bs.key=s.nextInt();
bs.search();
// if((res=bs.search())!=-1)
// {
// System.out.println("Element is found at position "+res);
// }else{
// System.out.println("Element not found");
// }
}
}