-
Notifications
You must be signed in to change notification settings - Fork 2
/
binarysearch.java
63 lines (63 loc) · 1.48 KB
/
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println("enter number of elements");
int size = scanner.nextInt();
System.out.println("enter number in sorted order");
int sortArr[]= new int[size];
int i;
for(i=0;i<size;i++)
{
sortArr[i]= scanner.nextInt();
}
System.out.println("enter number to be searched");
int key= scanner.nextInt();
Binarysearch bsearch = new Binarysearch(sortArr,key);
bsearch.search();
bsearch.result();
}
}
class Binarysearch
{
private int[] arr;
private int key;
public Binarysearch(int[] arr,int key)
{
this.arr = arr;
this.key=key;
}
public int search()
{
int top=0;
int bottom =arr.length-1;
while(top<=bottom)
{
int mid=(top+bottom)/2;
if(arr[mid]==key)
{
return mid;
}
else if(arr[mid]<key)
{
top=mid+1;
}
else
{
bottom=mid-1;
}
}
return -1;
}
protected void result()
{
int result=search();
if (result != -1) {
System.out.println(key + " found at index " + result);
} else {
System.out.println(key + " not found");
}
}
}