Fibonacci search algorithm (golden section search algorithm):
Mid = Low + F (k-1) - 1; F represents the Fibonacci sequence
Understanding of F(k-1)-1:
1. From the properties of Fibonacci sequence F [k] = F [k-1] + F [k-2], we can get (F[k]-1) = (F[k-1]-1) + (F[k-2]-1) +1.
This formula shows that as long as the length of the sequence table is F[K]-1, the table can be divided into two segments, F[k-1]-1 and F[k-2]-1, as shown in the figure above. So the middle position is mid = Low + F (k-1) - 12.
2) Similarly, each subparagraph can be divided in the same way
3. But the length of the sequence table n is not necessarily equal to F[k]-1, so it is necessary to increase the original length of the sequence table n to F[k]-1. The K value here can be obtained by the following code as long as F[k]-1 is equal to or greater than n. When the length of the sequence table increases, the new position (from n+1 to F[k]-1) is assigned to the value of n position.
Code implementation:
public static int[] fib(){ //We get a Fibonacci sequence of size 20. int[] f = new int[maxSize]; f[0] = 1; f[1] = 1; for (int i=2;i<maxSize;i++){ f[i] = f[i-1] + f[i-2]; } return f; } //Writing Fibonacci algorithm /** * @param arr array * @param key The value we need to look for * @return Returns the corresponding subscript, and returns - 1 without it * */ public static int fibSearch(int[] arr , int key){ int low = 0; int high = arr.length -1; int k = 0; //Subscripts representing Fibonacci partition values int mid = 0; //Store the value of mid int[] f = fib(); //Get the Fibonacci sequence //Obtain subscripts to Fibonacci partition values while(high > f[k]-1 ){ k++; } //Because the f[k] value may be larger than the length of a, we use the Array tool class to construct a new array and point to a //The deficiency will be supplemented by 0. int[] temp = Arrays.copyOf(arr,f[k]); //In fact, you need to fill temp with the last number of a arrays for (int i = high+1 ; i<temp.length ; i++){ temp[i] = arr[high]; } //Use the while loop to process and find our number key while (low <= high){//As long as this condition is satisfied, you can find it. mid = low + f[k - 1] - 1; if (key < temp[mid]){//Search left high = mid - 1; //Why k--? //Because all elements = front elements + back elements //f[k] = f[k-1] + f[k-2]; //Because there are f[k-1] elements in front of it, it can be divided into f[k-1] = f[k-2] + f[k-3]; //Find K before f[k-1]- //mid = f[k-1-1]-1 k--; }else if(key > temp[mid]){//Search right low = mid + 1; //Why k-2? //Because all elements = front elements + back elements //f[k] = f[k-1] + f[k-2]; //The latter f[k-2] can be split into f[k-1] = f[k-3] + f[k-4]; //Find k-=2 in front of f[k-2]. //mid = f[k - 1 - 2] - 1 k -= 2; }else {//find if (mid <= high){ return mid; }else{ return high; } } } return -1; }