First, let's look at an author's my book, a two-point lookup code
The return value is the subscript of key and returns -1template <class t>int binsearch if the key does not exist in A (t* a, const t &key, int lo, int hi) { int mid; while (Lo
It can be proved that the time complexity of the algorithm is O (NLOGN), considering the preceding coefficients, is approximately o (1.5nlogn).
However, there is still room for improvement in this implementation. Notice that the loop requires only 1 judgments to decide whether to go to the left, but 2 times to determine whether to go to the right. That is, in the left and right branch before the number of key code comparison.
The Fibonacci search was optimized for this. The Fibonacci number is used to divide the incoming array into gold so that the first half is less than the second half. In addition, the first half of the search required to continue searching for only one time, and enter the second half to continue to search for the required judgment is two times. In this way, this imbalance, which we artificially create, fuels the balance of search costs.
Template <class t>int fibsearch (T* a, const t &key, int lo, int hi) { int mid; fib fib (Hi-lo); //constructs a Fibonacci number class while (Lo Here we need to construct a Fibonacci number class. To write this class, in fact, only need an array, with the dynamic programming algorithm is very good to write, here no longer repeat.
Now that the algorithm is implemented, let's test the correctness of the two algorithms:
int main () {a=0,b=0; for (int i=0; i<=num; ++i) {A[i] = i; } for (int i=0; i<=num; ++i)//correctness validation {if (Binsearch (a,i,0,num)! = Fibsearch (a,i,0,num)) { cout<< "What a fucking day!" <<i<<endl; }} return 0;}
Algorithm performance comparison (by Fovwin):
Reference: 1. Mooc "Data structure and algorithm" by Deng Junhui, Tsinghua University, chapter II
2.wikipedia-fibonacci Search Technique (Https://en.wikipedia.org/wiki/Fibonacci_search_technique)
3. Is "Fibonacci search" really faster than two-point search? by Forwin (strongly recommended, C language implementation, code comments very clear-http://blog.csdn.net/fovwin/article/details/9077017)
"Binary search" and "Fibonacci Lookup" (Fibonacci search)