①创建一个数组arr,长度为8
int[] arr = {1,2,3,4,5,6,7,8};
②生成一组长度为10的斐波那契数组,长度自己定
(先说一下斐波那契数组有什么用,我的arr数组长度为8对吧,f(n)的值代表arr的长度,你就这么理解先,斐波那契数组的f(n) >= arr.length,为什么呢,
因为arr.length = 8,f(n) = f(n-1)+f(n-2),长度为8的数组arr可以分成前面5份和后面3份)
public static int[] getFei(int len){
int [] arr = new int[len];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < len; i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr;
}
不会教,写不下去大致这样
左移就是n--;原因是f(n-1)
右移就是n-2;原因是f(n-2)
package 查找.test;
import java.util.Arrays;
public class testfeibonaqie {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8};
int index = getIndex(arr, 0, arr.length-1, 8, getFei(10));
System.out.println(index);
}
public static int[] getFei(int len){
int [] arr = new int[len];
arr[0] = 1;
arr[1] = 1;
for (int i = 2; i < len; i++){
arr[i] = arr[i-1] + arr[i-2];
}
return arr;
}
public static int getIndex(int [] arr, int left, int right, int key, int[] f){
int low = 0;
int hight = arr.length-1;
int k = 0;
//求出k
while (hight+1 > f[k]){
k++;
}
int[] temp = Arrays.copyOf(arr, f[k]);
for(int i = hight + 1; i < temp.length; i++) {
temp[i] = arr[hight];
}
while (low <= hight){
int mid = low + f[k-1]-1;
if (key < temp[mid]){
hight = mid - 1;
k--;
}
else if (key > temp[mid]){
low = mid+1;
k-=2;
}
else {
if(mid <= hight) {
return mid;
} else {
return hight;
}
}
}
return -1;
}
}