Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. //PROGRAM CODE 9.5 // Function to find nth Fibonacci number
  2. #include<iostream.h>
  3. #include<conio.h>
  4. #define max 20
  5.  
  6. int fibo(int n)
  7. {
  8. if(n==0 || n==1)
  9. return 1;
  10. else
  11. return(fibo(n-1)+fibo(n-2));
  12. }
  13. // Function for Fibonacci search
  14. int Fibonacci_Search(int A[],int n, int key)
  15. {
  16. int f1,f2,t,mid,j,f;
  17. j=1;
  18. while(fibo(j) <= n)
  19. { //find fib(j) such that fib(j)>=n
  20. j++;
  21. }
  22. f=fibo(j);
  23. f1=fibo(j-2); //find lower Fibonacci numbers
  24. f2=fibo(j-3); // f1=fib(j-2), f2=fib(j-3)
  25. mid=n-f1+1;
  26. while(key!=A[mid]) // if not found
  27. {
  28. if(mid<0||key>A[mid])
  29. { //look in lower half
  30. if(f1 == 1)
  31. return -1;
  32. mid = mid+f2; //decrease Fibonacci numbers
  33. f1 = f1-f2;
  34. f2 = f2-f1;
  35. }
  36. else
  37. { //look in upper half
  38. if(f2 == 0) //if not found return -1
  39. return -1;
  40. mid = mid-f2; //decrease fibonacci numbers
  41. t = f1-f2; //this time, decrease more
  42. f1 = f2; //for smaller list
  43. f2 = t;
  44. }
  45. }
  46. return mid;
  47. }
  48.  
  49. void main()
  50. {
  51. int A[max], ele,size,i,ans;
  52. clrscr();
  53. cout<<"\n\n Eneter the size of the array:";
  54. cin>>size;
  55. cout<<"\n\n Enter elements:\n";
  56. for (i=0;i<size;i++)
  57. {
  58. cin>>A[i];
  59. }
  60. cout<<"\n\n Enter the element to be search = ";
  61. cin>>ele;
  62.  
  63. ans=Fibonacci_Search(A,size,ele);
  64.  
  65. if(ans!=-1)
  66. cout<<"\tElement "<<ele<<" found at position "<<ans+1;
  67. else
  68. cout<<"\tElement "<<ele<<" Not found in the given array.";
  69. getch();
  70. }
  71. /*********************OUTPUT*********************************
  72. Eneter the size of the array:5
  73.  
  74. Enter elements:
  75. 2 3 4 5 6
  76. Enter the element to be search = 7
  77. Element 7 Not found in the given array.
  78.  
  79. Eneter the size of the array:5
  80.  
  81. Enter elements:
  82. 1 2 3 4 5
  83.  
  84. Enter the element to be search = 4
  85. Element 4 found at position 4
  86. ************************************************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement