-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary.c
58 lines (58 loc) · 1.01 KB
/
binary.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
#include<stdio.h>
int sort(int a[],int n)
{
int temp,i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a[i];
}
int search(int a[],int x,int n,int l,int r)
{
int i,m;
if (l>r)
return -1;
while(l<=r)
{
m=(l+r)/2;
if(a[m]==x)
return m;
else if(a[m]>x)
return search(a,x,n,l,m-1);
else
return search(a,x,n,m+1,r);
}
}
void main()
{
int a[40],i,x,n,b;
printf("enter the limit");
scanf("%d",&n);
printf("enter %d elements",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
sort(a,n);
printf("sorted array is: ");
for ( i = 0; i < n; i++)
{
printf("%d\t",a[i]);
}
printf("\n enter the no to be searched");
scanf("%d",&x);
b=search(a,x,n,0,n-1);
if(b>0)
printf("element found at %d",(b+1));
else
printf("not found");
}