Fibonacci Lookup algorithm Complete C code

Source: Internet
Author: User

/* 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.