-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path49.c
68 lines (59 loc) · 1.08 KB
/
49.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
67
68
//Program to implement binary search recursively
#include<stdio.h>
//Sort the elements
void sort(int arr[],int n)
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(arr[j+1]<arr[j])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf("\nSorted array:\n");
for(int i=0;i<n;i++)
{
printf("\t%d",arr[i]);
}
}
int binarysearch(int arr[],int n,int key,int l,int h)
{
int mid;
if(l>h)
return -1;
mid=(l+h)/2;
if(arr[mid]==key)
return mid;
else if(key>arr[mid])
binarysearch(arr,n,key,mid+1,h);
else
binarysearch(arr,n,key,l,mid-1);
}
int main(void)
{
int arr[20],n,k,key,i,j,c;
int l=0,h;
printf("\nEnter the number of elements in the array:");
scanf("%d",&n);
printf("\nEnter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
h=n-1;
sort(arr,n);
printf("\nEnter the element to be searched:");
scanf("%d",&key);
c=binarysearch(arr,n,key,l,h);
if(c==-1)
printf("\nElement not found \n");
else
printf("\nElement found at index posiion %d \n ",c);
return 0;
}