-
Notifications
You must be signed in to change notification settings - Fork 19
/
BinarySearch.java
111 lines (86 loc) · 2.4 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import java.util.Scanner;
/* Java Program for Binary Search on Unsorted Array */
public class BinarySearch {
//----------------Function to Sort Array-------------------
static int[] sorted(int arr[])
{
int l,max,temp;
l=arr.length;
for(int i=0;i<l;i++)
{
for(int j=i+1;j<l;j++)
{
if(arr[i]>arr[j])
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
return arr;
}
//------------function to search key in array-------------
static int binarysearch(int a[],int key)
{
int beg,l,end,mid;
l=a.length;
beg=0;
end=l-1;
mid=(beg+end)/2;
while(beg<=end)
{
if(a[mid]<key)
{
beg=mid+1;
mid=(beg+end)/2;
}
else if(a[mid]==key)
{
break;
}
else
{
end=mid-1;
mid=(beg+end)/2;
}
if(beg>end)
{
mid=0;
}
}
return mid;
}
public static void main(String[] args) {
int i,n,b[],key,c;
System.out.print("Enter size of array: ");
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
int a[]=new int[n];
//---------Enter values to array-------------
for(i=0;i<n;i++)
{
System.out.print(i+1 +" element : ");
a[i]=sc.nextInt();
}
System.out.print("");
//-----------------Sort the array--------------------
b=sorted(a);
for(i=0;i<n;i++)
{
System.out.println(i+1 +" element : "+b[i]);
}
//---------------Enter search key u want to find-----------
System.out.println("Enter the number u want to search: ");
key=sc.nextInt();
c=binarysearch(b,key);
if(c==0)
{
System.out.println("Sorry,Key doesn't exist in the array");
}
else
{
System.out.println("Position of element is : "+(c+1));
}
}
}