Binary Search Using Recursion
Program Code:
#include<stdlib.h>
void sorting(int *a,int size)
{
int i,j,temp;
for(i=0;i<=size-1;i++)
{
for(j=0;j<=size-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
int b_search(int *a,int beg,int end,int k)
{
int mid;
if(beg>end)
{
return (-1);
}
mid=(beg+end)/2;
if(k==a[mid])
{
return mid;
}
else if(k<a[mid])
{
return b_search(a,beg,mid-1,k);
}
else
{
return b_search(a,end,mid+1,k);
}
}
int main()
{
int *a,size,beg,end,l,sid,k;
printf("Enter the size of the array\n");
scanf("%d",&size);
a=(int*)malloc(size*sizeof(int));
printf("Enter the elements\n");
for(l=0;l<size;l++)
{
scanf("%d",&a[l]);
}
sorting(a,size);
printf("The sorted elements are\n");
for(l=0;l<size;l++)
{
printf("%d\n",a[l]);
}
printf("Entr the search number\n");
scanf("%d",&k);
beg=0;
end=size-1;
sid=b_search(a,beg,end,k);
if(sid!=-1)
{
printf("The search number is found\n");
}
else
{
printf("The search number is not found\n");
}
return 0;
}
Hence , //comming soon
Input:
Enter the size of the array
5
Enter the elements
5
4
3
2
1
The sorted elements are
1
2
3
4
5
Entr the search number
6
Output:
The search number is not found
No comments:
Post a Comment