斐波那契查找是属于二分查找的一种,提高了查找效率
查找方式在百度词条中已经说的很清楚了这里就不再写了,直接走代码,体验一下0.618的神奇
import java.util.Arrays; public class FibonacciSearch { public static int maxSize = 20; public static void main(String[] args) { int[] arr = {1, 8, 10, 89, 1000, 1234}; System.out.println(fibSearch(arr,10)); } public static int[] fib() { 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; } //非递归 public static int fibSearch(int[] a, int key) { int low = 0; int high = a.length - 1; int k = 0;//斐波那契分割数值下标 int mid = 0;//mid值 int f[] = fib(); while (high > f[k] - 1) { k++; } //不足部分用0填充 int[] temp = Arrays.copyOf(a, f[k]); //用a数组最后的数填充temp for (int i = high + 1; i < temp.length; i++) { temp[i] = a[high]; } while (low <= high) { mid = low + f[k - 1] - 1; if (key < temp[mid]) { high = mid - 1; k--; } else if (key > temp[mid]) { low = mid + 1; k -= 2; } else { if (mid<=high){ return mid; } else { return high; } } } return -1; } }
来源:https://www.cnblogs.com/bingbug/p/12275913.html