斐波那契数列查找

222 阅读1分钟
import java.util.Arrays;

public class FibonacciSearch {
    static int maxSize=20;
    public static void main(String[] args) {
        
    }

## 非递归方法得到一个斐波那契数列 ##
    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;
    }

## 编写斐波那契查找算法 ##
    //a是数组,key是我们需要查找的关键值,返回对应的下标
    public static int fibSearch(int[] a,int key){
        int low=0;
        int high=a.length-1;
        int k=0;//表示斐波那契分割数值的下标
        int mid=0;
        int f[]=fib();//获取到斐波那契数列
        //获取到斐波那契获取分割数值的下标
        while (high>f[k]-1){
            k++;
        }
        //因为f[k]的值可能大于数组的长度,因此我们需要使用一个Arrays类,构造一个新的数组,并指向a[]       
        int[] temp= Arrays.copyOf(a,f[k]);
        //需要使用a数组的最后的数来填充temp
        //temp={1,8,10,89,1000,1234} => {1,8,10,89,1000,1234,1234,1234,1234}
        for (int i=high+1;i<temp.length;i++){
            temp[i]=a[high];
        }
        //使用while来循环处理,找到key
        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;
    }
}