The core idea of the Fibonacci search is:
1) when Key=a[mid], find success;
2) when Key<a[mid], the new search range is the first low to the mid-1, at this time the number of the range is f[k-1]-1, that is, the length of the left of the array, so in [Low, f[k-1]-1] within the scope of the search;
3) when Key>a[mid], the new lookup range is mid+1 to high, at this time the number of ranges is f[k-2]-1, which is the length of the right of the array, so look in the [f[k-2]-1] range.
Code:
Fibonacci Find//Xin Yang # include <stdio.h> #include <stdlib.h> #define MAXN 20/* * Generate Fibonacci Sequence * */void Fibonacci (int *f) {int I;f[0] = 1;f[1] = 1;for (i = 2;i < MAXN; ++i) f[i] = F[i-2] + f[i-1];} /* * Find * */int fibonacci_search (int *a, int key, int n) {int i, low = 0, high = n-1;int mid = 0;int k = 0;int F[MAXN]; Fibonacci (F); while (n > F[k]-1)//calculates n in Fibonacci's sequence ++k;for (i = N;i < F[k]-1;++i)//Array completion a[i] = A[high];while (Low < = high) {mid = low + f[k-1]-1; Gold split according to Fibonacci sequence if (A[mid] > key) {high = Mid-1;k = K-1;} else if (A[mid] < key) {low = mid + 1;k = k-2;} Else{if (Mid <= High)//If True, locate the corresponding position return mid;elsereturn-1;}} return 0;} int main () {int A[MAXN] = {5,15,19,20,25,31,38,41,45,49,52,55,57};int K, res = 0;printf ("Please enter the number to find: \ n"); scanf ("%d", &K); res = Fibonacci_search (a,k,13); if (res! =-1) printf ("element found at%d of the array:%d\n", res + 1, k); elseprintf ("element not found in array:%d \ n ", k); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Data structure---C language implementation Fibonacci lookup