Full C code of the Fibonacci Search Algorithm
/* Fibonacci Search Method */# include
# Include
Int Fib (int k) {if (1 = k | 2 = k) return 1; elsereturn Fib (k-1) + Fib (K-2 );} int FibSearch (int * a, int n, int key) {int k = 1; int nFib; int * B; int low, mid, high; while (Fib (k) <n) // find Fib [k] k ++; nFib = Fib (k); B = (int *) realloc (a, sizeof (int) * nFib ); // expand the array size for (int I = n; I
Key) {k = k-1; high = mid;} if (B [mid] <key) {k = K-2; low = mid + 1 ;} if (B [mid] = key) {if (mid> = n-1 & mid <= nFib) return n-1; return mid;} mid = low + Fib (k-1) -1 ;}if (low = key) return low; return-1 ;}int main () {int n; printf ("Enter the size of the target array: \ n "); scanf (" % d ", & n); int * a = (int *) malloc (sizeof (int) * n ); printf ("Enter % d ordered integers: \ n", n); for (int I = 0; I
= 0) printf ("LOCATION % d found successfully! \ N ", search); elseprintf (" % d not found! \ N ", key); return 0 ;}
In this Code, the core of the Fibonacci search is: 1) when key = a [mid], the search is successful; 2) When keya [mid, the new search range is mid + 1 to high, and the number of ranges is F [K-2.
4) if the last two elements are matched, the two elements are directly compared with the keywords.