Python写出斐波那契二分检索,即使用斐波那契数列二分有序序列,查找某给定元素,找到返回下标,找不到返回-1
时间: 2024-02-06 22:04:42 浏览: 75
以下是一个基于斐波那契数列的二分查找程序的实现:
```python
def fibonacci_search(arr, x):
n = len(arr)
fib2 = 0
fib1 = 1
fib = fib2 + fib1
# Find the smallest Fibonacci number greater than or equal to n
while fib < n:
fib2 = fib1
fib1 = fib
fib = fib2 + fib1
# Marks the eliminated range from front
offset = -1
# While there are elements to be inspected
while fib > 1:
# Check if fib2 is a valid location
i = min(offset + fib2, n - 1)
# If x is greater than the value at index fib2, cut the subarray array from offset to i
if arr[i] < x:
fib = fib1
fib1 = fib2
fib2 = fib - fib1
offset = i
# If x is less than the value at index fib2, cut the subarray after i+1
elif arr[i] > x:
fib = fib2
fib1 = fib1 - fib2
fib2 = fib - fib1
# If x is equal to the value at index fib2, return the index
else:
return i
# Compare the last element with x
if fib1 and offset < n-1 and arr[offset+1] == x:
return offset + 1
# If the element was not found, return -1
return -1
```
该函数接受一个数组和一个要查找的值x作为参数,并返回x在数组中的下标,如果x不存在于数组中,则返回-1。
该算法的时间复杂度为 O(log n)。虽然它比传统的二分查找稍微慢一些,但它的优点是可以在没有指针引用的情况下进行搜索,因此它可以用于非随机存取的数据结构(例如磁盘存储)。此外,该算法还具有与二分查找相同的优点,即时间复杂度为 O(log n)。
阅读全文