# 费氏搜索法

792人阅读 评论(0)

/**
* http://www.caterpillar.onlyfun.net/Gossip/AlgorithmGossip/FibonacciSearch.htm
* <p>Title: </p>
* <p>Description: </p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/

public class FibonacciSearch {
public static int search(int[] number, int des) {
int[] fib = createFibonacci(number.length);
int x = findX(fib, number.length + 1, des);
int m = number.length - fib[x];
x--;
int i = x;
if (number[i] < des)
i += m;
while (fib[x] > 0) {
if (number[i] < des)
i += fib[--x];
else if (number[i] > des)
i -= fib[--x];
else
return i;
}
return -1;
}

private static int[] createFibonacci(int max) {
int[] fib = new int[max];
for (int i = 0; i < fib.length; i++) {
fib[i] = Integer.MIN_VALUE;
}
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < max; i++)
fib[i] = fib[i - 1] + fib[i - 2];
return fib;
}

private static int findX(int[] fib, int n, int des) {
int i = 0;
while (fib[i] <= n)
i++;
i--;
return i;
}

public static void main(String[] args) {
int[] number = {
1, 4, 2, 6, 7, 3, 9, 8};
QuickSort.sort(number);
int find = FibonacciSearch.search(number, 3);
if (find != -1)
System.out.println("找到數值於索引" + find);
else
System.out.println("找不到數值");
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：26128次
• 积分：381
• 等级：
• 排名：千里之外
• 原创：10篇
• 转载：18篇
• 译文：0篇
• 评论：3条
最新评论
javascript,ajax