/*Find area and population of given city using Linear and Binary Search*/
#include <stdio.h>
#include<string.h>
typedef struct city
{
char cty[30];
long int area,popu;
}city;
void sort(city a[30],int n);
int binsearch(city a[30],int i ,int j,char key[30]);//Recursive
int linsearch(city a[30],int n , char key[30]);
int main()
{
int n,i,result,op;
char key[30];
city a[30];
printf("\n Enter No. of cities : ");
scanf("%d" ,&n);
printf("\n Enter a list of %d cities with their area and population : ",n);
for(i=0;i<n;i++)
scanf("%s%ld%ld",a[i].cty,&a[i].area,&a[i].popu);
fflush(stdin);
printf("\n Enter the city to be searched :");
scanf("%s",key);
do
{
printf("\n1)Linear Search\n2)Binary Search\n3)Enter city to be searched");
printf("\n4)Quit");
printf("\nEnter Your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1:
result=linsearch(a,n,key);
if(result==-1)
printf("\n Not found ");
else
{
printf("\n City :%s Area:%ld Population:%ld",key,a[result].area,a[result].popu);
}
break;
case 2:
sort(a,n);
result=binsearch(a,0,n-1,key);
if(result==-1)
printf("\nNot found ");
else
{
printf("\n City :%s Area:%ld Population:%ld",key,a[result+1].area,a[result+1].popu);
}
break;
case 3: printf("\n Enter the city to be searched :");
scanf("%s",key);
break;
}
}while(op!=4);
}
int binsearch(city a[],int i, int j,char key[])
{
int c;
if(i>j)
return(-1);
c=(i+j)/2;
if(strcasecmp(key,a[c].cty)==0)
return(c);
if(strcasecmp(key,a[c].cty)>0)
return(binsearch(a,c+1,j,key));
return(binsearch(a,i,c-1,key));
}
int linsearch(city a[],int n , char key[])
{
int i;
for(i=0;i<n;i++)
{
if(strcasecmp(a[i].cty,key)==0)
return(i+1);
}
return(-1);
}
void sort(city b[],int n)
{int i,j;
city temp;
for(i=1;i<n;i++)
for(j=0;j<n-i;j++)
if(strcasecmp(b[j].cty,b[j+1].cty)>0)
{ temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
No comments:
Post a Comment