-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_search.java
67 lines (67 loc) · 1.26 KB
/
Binary_search.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
package practicetime;
import java.util.Scanner;
public class Binary_search {
public static void main(String args[])
{
int a[]=new int[20];
Scanner sc=new Scanner(System.in);
int i,temp=0,count=0;;
System.out.println(" Enter the number of elements you want to input ");
int n=sc.nextInt();
System.out.println(" Enter the numbers ");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.print(" The Elements are ---\n");
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}
System.out.print("\n The Sorted Elements are ---\n");
for(i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}}
System.out.print(" Array is - \n");
for(int k=0;k<n;k++)
{
System.out.print(a[k]+" ");
}
}
for(i=0;i<n;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n Enter the Number to be Searched ");
int s=sc.nextInt();
int beg=1,end=n,mid=0;
mid=(beg+end)/2;
while(beg<=end)
{
if(s>a[mid])
{
beg=mid+1;
}
else if(s<a[mid])
{
end=mid-1;
}
else if(s==a[mid])
{
System.out.println(" Number found at Location - "+mid);
count++;
break;
}mid=(beg+end)/2;
}
if(count==0)
System.out.println(" Sorry Not Found ");
sc.close();
}
}