斐波那契查找
import time def fibonacci_sequence(num: int): # 按照待查找数列的大小,动态生成斐波那契数列 a, b = 0, 1 while a <= num - 1: yield a a, b = b, a + b yield a return def fibonacci_search(a: [], n: int, key: int) -> int: # 斐波那契查找 low, high, k = 1, n, 0 F = fibonacci_sequence(n) dynamic_F = [] for item in F: dynamic_F.append(item) while n > dynamic_F[k] - 1: k += 1 for i in range(n, dynamic_F[k] - 1): a.append(a[n]) while low <= high: mid = low + dynamic_F[k - 1] - 1 if key < a[mid]: high = mid - 1 k -= 1 elif key > a[mid]: low = mid + 1 k -= 2 else: if mid <= n: return mid else: return n return 0 if __name__ == '__main__': # a = [1 ,11, 53, 100, 102, 443, 445, 446, 654, 997, 999, 1001, 1120, 1981, 2000, 2005, 2007] start_time = time.time() a =[i for i in range(100000)][::5] print(a) key = 1005 index=fibonacci_search(a, len(a) - 1, key) print("key's index is:{},value is {}".format(index,a[index]) ) end_time=time.time() print("数据长度",len(a)) print("開始時間",start_time) print("結束時間",end_time)
查找方式