/* Fibonacci Lookup Method */#include <stdio.h> #include <stdlib.h>int Fib (int k) {if (1 = = k | | 2 = = k) return 1;elsereturn F IB (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++;n FIB = fib (k); b = (int *) realloc (A, sizeof (int) *nfib);//Expand the size of the array for (int i=n; i<nfib; i++)//with the last element to supplement the array b[i] = b[n-1]; Low = 0;high = Nfib-1;mid = low + Fib (k-1) -1;while (Low < MID) {//last two digits left, low = = Mid, can be processed after loop if (B[mid] > 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);p rintf ("Enter%d ordered integers "N", "for" (int i=0; i<n; i++) scanf ("%d", &a[i]);p rintf ("Please enter keywords to find: \ n"); int key;int search;scanf ("%d", & key); search = Fibsearch (A, n, key); if ( Search >= 0) printf ("Find successful!\n at location%d", search), elseprintf ("Not Found%d!\n", key); return 0;}
The core of Fibonacci lookup in this code is: 1) when Key=a[mid] is found successfully, 2) when Key<a[mid], the new look-up range is low to mid, the number of ranges is f[k-1], 3) when key >a[mid], the new look-up range is mid+1 to the first, and the number of scopes is f[k-2].
4) If the last two elements are matched, the two elements are compared directly to the keyword.
Fibonacci Lookup algorithm Complete C code