-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
71 lines (58 loc) · 1.09 KB
/
BinarySearch.java
File metadata and controls
71 lines (58 loc) · 1.09 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
// Binary Search Array
import java.util.*;
public class BinarySearch
{
public static void main(String args[])
{
int i,n,c;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Total number of Element: ");
n=sc.nextInt();
int a[]=new int[n];
System.out.println("ENter the element: ");
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter the element U want to Search: ");
c=sc.nextInt();
int low=0;
int high=n-1;
int mid;
// sorting
int temp=0;
System.out.println("Sorted Array: ");
for(i=0;i<n;i++)
{
for(int j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
System.out.println();
for(i=0;i<n;i++)
System.out.print(" "+a[i]+" ");
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]<c)
{
low=mid+1;
}
else if(a[mid]>c)
high=mid-1;
else if(c==a[mid])
{
System.out.println("Element found at position "+(++mid));
break;
}
else if(c!=a[mid]) {
System.out.println("Emelment Not found!");
break;
}
}
}
}