Full C code of the Fibonacci Search Algorithm

Source: Internet
Author: User

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.


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.