package org.structure.search;
import java.util.Arrays;
/**
* 斐波那契数列查找
* @author cjj_1
* @date 2020-08-19 9:33
*/
public class FibonacciSerarch {
public static void main(String[] args) {
int[] arr = {1,34,57,89,90,100,101};
int i = fibSearch(arr,101);
System.out.println(i+":是下标");
}
//返回一个fibnnacci数组
public static int[] fib(int k){
int f[] = new int[k];
f[0] =1;
f[1] = 1;
for(int index =2;index < k;index++){
f[index] = f[index-1]+f[index-2];
}
return f;
}
public static int fibSearch(int[] arr,int keyValue){
int low = 0;
int hight = arr.length-1;
int k =0;
int[] f = fib(20);
//寻找对应的K
while (hight>f[k]-1){
k++;
}
//arr 数组的大小<f[k]时
int[] temp = Arrays.copyOf(arr,f[k]);
for(int index = hight+1;index < f[k];index++){
temp[index]=arr[hight];
}
while (low<=hight){
int mid = low+f[k-1]-1;
if(keyValue<temp[mid]){
hight = mid-1;
k--;
}else if(keyValue>temp[mid]){
low = mid+1;
k-=2;
}else{
return mid;
}
}
return -1;
}
}
斐波那契查找算法
最新推荐文章于 2024-08-13 10:59:39 发布