Thursday, August 27, 2009

Fibonacci Search

#include
#include
void main()
{
int age[50],n,j,i,sage,tage,flag=0;
int p,q,m,t;
char yn,name[50][50],tname[50];
int fib(int);
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 Fibonacci 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);
i=fib(n);
p=fib(n-1);
q=fib(n-2);
m=n+1-(i+p);
if(sage>age[i])
i=i+m;
while(i!=0)
{
if(sage {
if(q==0)
i=0;
else
{
i=i-q;
t=p;
p=q;
q=t-q;
}
}
if(sage==age[i])
{
printf("\n\tS.No : %d\n\tName : %s\n\tAge : %d\n",i,name[i],age[i]);
flag=1;
break;
}
if(sage>age[i])
{
if(p==1)
i=0;
else
{
i=i+q;
p=p-q;
q=q-p;
}
}
}
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();
}
int fib(int f)
{
if(f<=1)
return(f);
else
return(fib(f-1)+fib(f-2));
}

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 : 3
S.No : 3
Name : a
Age : 3
Do you Want to Continue (Y/y) :n


No comments:

Post a Comment