forked from ayushisheode/HacktoberFest-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary search.c
66 lines (64 loc) · 1.31 KB
/
binary search.c
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
#include<stdio.h>
int main()
{
int a[100],n,i;
printf("\n Enter no. of elements : ");
scanf("%d",&n);
printf("\n Enter array : ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
//Arrange array in ascending order.
int temp,j;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\n array in asc. order is : ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
//Binary search code.
int l=0,h=n-1,m=(l+h)/2; //l,h,m contain indexes.
int e,flag;
printf("\n Enter element to search : ");
scanf("%d",&e);
while(l<=h)
{
if(e==a[m])
{
flag=1;
break;
}
else if(e>a[m])
{
l=m+1;
m=(l+h)/2;
}
else if(e<a[m])
{
h=m-1;
m=(l+h)/2;
}
}
if(flag==1)
{
printf("\n Element if found.");
printf("\n Position of element in sorted array is %d.",m+1);
}
else
printf("\n element is not in array.");
printf("\n\n");
return 0;
}