1 #include "pch.h"
2 #include <iostream>
3 const int max_num = 50;
4 //构造一个fib数列
5 void ProduceFib(int *fib, int size) {
6 int i;
7 fib[0] = 1;
8 fib[1] = 1;
9 for (i = 2; i < size; i++) {
10 fib[i] = fib[i - 1] + fib[i - 2];
11 }
12 }
13 //fib查找
14 int FibSearch(int *data, int length, int serch_value) {
15 int lo, hi, mid, i, j, fib[max_num];
16 lo = 0;
17 hi = length - 1;
18 i = 0;
19 ProduceFib(fib, max_num);
20 //找到最接近数组长度的fib
21 while (hi > fib[i])
22 {
23 i++;
24 }
25 //补全有序数列
26 for (j = length; j < fib[i]; j++) {
27 data[j] = data[length-1];
28 }
29 while (lo<=hi)
30 {
31 mid = lo + fib[i - 1] - 1;
32 if (serch_value < data[mid]) {
33 hi = mid-1;
34 i = i - 1;
35 }
36 else if (data[mid] < serch_value) {
37 lo = mid + 1;
38 i = i - 2;
39 }
40 else if(data[mid]==serch_value)
41 if (mid < length - 1) {
42 return mid;
43 }
44 else
45 {
46 return length - 1;
47 }
48 }
49 return mid;
50 }
51 int main()
52 {
53 int arr[11] = { 1,1,1,2,2,2,3,3,4,4,5 };
54 size_t num=FibSearch(arr, 11, 3);
55 std::cout << num;
56 }
编译会提示arr栈被破环了,因为你自行扩充了arr的长度,但是不影响你看结果。
原文:https://www.cnblogs.com/Royzzzzz/p/11067307.html