Thursday, August 27, 2009

Binary Search

#include
#include
void main()
{
int age[50],n,j,i,sage,tage,flag=0;
int low,mid,high;
char yn,name[50][50],tname[50];
clrscr();
printf("Enter Number of Student : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter Name of Student %d : ",i);
scanf("%s",name[i]);
printf("Enter Age of %s : ",name[i]);
scanf("%d",&age[i]);
}
do
{
clrscr();
flag=0;
/*For Binary Search First We Must Sort Array*/
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(age[i] {
tage=age[i];
age[i]=age[j];
age[j]=tage;
strcpy(tname,name[i]);
strcpy(name[i],name[j]);
strcpy(name[i],tname);
}
}
printf("\tS.No\tNAME\tAGE");
for(i=1;i<=n;i++)
{
printf("\n\t%d\t%s\t%d",i,name[i],age[i]);
}
printf("\nEnter Student Age to Find Name and S.No : ");
scanf("%d",&sage);
low=1;
high=n;
while(low<=high)
{
mid=(low+high)/2;
if(sage high=mid-1;
if(sage>age[mid])
low=mid+1;
if(sage==age[mid])
{
printf("\n\tS.No : %d\n\tName : %s\n\tAge : %d\n",mid,name[mid],age[mid]);
flag=1;
break;
}
}
if(flag==0)
printf("\nStudent Age %d is not in our record.",sage);
printf("\nDo you Want to Continue (Y/y) : ");
yn=getchar();
}while((yn=='Y')(yn=='y'));
getch();
}

Output
Enter Number of Student : 3
Enter Name of Student 1 : C
Enter Age of C : 3
Enter Name of Student 2 : B
Enter Age of B : 2
Enter Name of Student 3 : A
Enter Age of A : 1
S.No NAME AGE
1 C 1
2 B 2
3 A 3
Enter Student Age to Find Name and S.No : 2
S.No : 2
Name : B
Age : 2Do you Want to Continue (Y/y) :N

No comments:

Post a Comment