Saturday, September 3, 2011

BINARY SEARCH


/*BINARY SEARCH for students*/

#include <stdio.h>
#include<string.h>

int stepcount=0,swapcount=0,compcount=0;

int binsearch(char a[][30],int i ,int j,char key[]);//Recursive
int main()
 {
   int n,i,result;
   char a[30][30],key[30];
   printf("\n Enter No. of students : ");
   scanf("%d" ,&n);
   printf("\n Enter a sorted list(alphabetical order) of %d students : ",n);
   for(i=0;i<n;i++)
scanf("%s",a[i]);
   printf("\n Enter the the student to be searched : ");
   scanf("%s",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(char a[][30],int i, int j,char key[30])
{
   int c;
   if(i>j)
{
 compcount++;
 stepcount+=2;
 return(-1);
}
   c=(i+j)/2;
   if(strcasecmp(key,a[c])==0)
{
 compcount++;
 stepcount+=2;
 return(c);
}
   if(strcasecmp(key,a[c])>0)
{

 stepcount++;
 return(binsearch(a,c+1,j,key));
}
  
   stepcount++;
   return(binsearch(a,i,c-1,key));
 }

No comments:

Post a Comment