/*BINARY SEARCH for numbers */
#include <stdio.h>
int stepcount=0,swapcount=0,compcount=0;
int binsearch(int a[],int i ,int j,int key);//Recursive
int main()
{
int a[30],key,n,i,result;
printf("\n Enter No. of elements : ");
scanf("%d" ,&n);
printf("\n Enter a sorted list of %d elements : ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Enter the the element to be searched : ");
scanf("%d",&key);
result=binsearch(a,0,n-1,key);
if(result==-1)
printf("\n Not found ");
else
printf("\n Found at location= %d",result+1);
printf("\n No. of steps= %d",stepcount);
printf("\n No. of swaps= %d", swapcount);
printf("\n No. of comparisons= %d",compcount);
}
int binsearch(int a[],int i, int j,int key)
{
int c;
if(i>j)
{
compcount++;
stepcount+=2;
return(-1);
}
c=(i+j)/2;
if(key==a[c])
{
compcount++;
stepcount+=2;
return(c);
}
if(key>a[c])
{
stepcount++;
return(binsearch(a,c+1,j,key));
}
stepcount++;
return(binsearch(a,i,c-1,key));
}
No comments:
Post a Comment