#include<stdio.h>
int Binarysearch(int a[50],int n,int key,int start,int end);
main()
{
int a[50],i,j,n,t,key;
printf("Enter the size of the array:\n");
scanf("%d",&n);
printf("Enter elements into the array:");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n-1;i++)
{
for(j=1;j<=n-i;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("The sorted array is: ");
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
printf("\nEnter the element to be searched: ");
scanf("%d",&key);
int Pos, start=0 , end=n-1;
Pos=Binarysearch(a,n,key,start,end);
if(Pos==-1)
{
printf("Element Not Found!!");
}
else
{
printf("%d found at %d",key,Pos);
}
}
int Binarysearch(int a[50],int n,int key,int start,int end)
{
int mid;
if(start<=end)
{
mid=(start+end)/2;
if(a[mid]==key)
{
return mid;
}
else if(a[mid]>key)
{
return Binarysearch(a,n,key,start,mid-1);
}
else
{
return Binarysearch(a,n,key,mid+1,end);
}
}
if(start>end)
{
return -1;
}
}
Note: Need to be arranged in compiler after copied
OutPut:
Enter the size of the array:
5
Enter elements into the array:8
2
5
4
7
The sorted array is: 2 4 5 7 8
Enter the element to be searched: 7
7 found at 4