1 Star 1 Fork 1

xcc/structures-and-algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
FibonacciSearch.java 1.88 KB
一键复制 编辑 原始数据 按行查看 历史
xcc 提交于 5年前 . 修改包名
package com.xcc.dataStructures.demo07_search;
import java.util.Arrays;
/**
* 斐波那契查找算法
*
* @author xiaocheng
* @date 2020/12/9 15:53
*/
public class FibonacciSearch {
private static Integer size = 10;
public static void main(String[] args) {
int[] arr = {1, 8, 10, 89, 1000, 1234};
System.out.println(fibonacciSearch(arr, 1235));
}
/**
* 定义斐波拉契数组
*/
public static int[] fib() {
if (size < 2) {
throw new RuntimeException("定义的数组长度必须大于2");
}
int[] f = new int[size];
f[0] = 1;
f[1] = 1;
for (int i = 2; i < size; i++) {
f[i] = f[i - 1] + f[i - 2];
}
return f;
}
/**
* 查找
*/
public static int fibonacciSearch(int[] arr, int val) {
int left = 0;
int right = arr.length - 1;
int[] f = fib();
int k = 0;
while (right > f[k] - 1) {
k++;
}
//拷贝临时数组 比原始数组长的部分会直接用0补齐
int[] temp = Arrays.copyOf(arr, f[k]);
//将长于arr部分用高位值补齐
for (int i = right + 1; i < temp.length; i++) {
temp[i] = arr[right];
}
int mid = 0;
while (left <= right) {
mid = left + f[k - 1] - 1;
if (val < temp[mid]) {
//向左找
right = mid - 1;
k--;
} else if (val > temp[mid]) {
//向右找
left = mid + 1;
k -= 2;
} else {
if (mid < right) {
return mid;
} else {
//如果查到的是扩容之后的数值,就直接返right
return right;
}
}
}
return -1;
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/xiaocheng0902/structures-and-algorithm.git
git@gitee.com:xiaocheng0902/structures-and-algorithm.git
xiaocheng0902
structures-and-algorithm
structures-and-algorithm
master

搜索帮助