二分查找
# 返回 x 在 arr 中的索引,如果不存在返回 -1
def binarySearch(arr, l, r, x):
# 基本判断
if r >= l:
mid = int(l + (r - l) / 2)
# 元素整好的中间位置
if arr[mid] == x:
return mid
# 元素小于中间位置的元素,只需要再比较左边的元素
elif arr[mid] > x:
return binarySearch(arr, l, mid - 1, x)
# 元素大于中间位置的元素,只需要再比较右边的元素
else:
return binarySearch(arr, mid + 1, r, x)
else:
# 不存在
return -1
# 测试数组
arr = [2, 3, 4, 10, 40]
x = 10
# 函数调用
result = binarySearch(arr, 0, len(arr) - 1, x)
if result != -1:
print("元素在数组中的索引为 %d" % result)
else:
print("元素不在数组中")
# 时间复杂度O(log n)
线性查找(顺序查找)
def search(arr, n, x):
for i in range(0, n):
if (arr[i] == x):
return i
return -1
# 在数组 arr 中查找字符 D
arr = ['A', 'B', 'C', 'D', 'E']
x = 'D'
n = len(arr)
result = search(arr, n, x)
if (result == -1):
print("元素不在数组中")
else:
print("元素在数组中的索引为", result)
斐波那契查找
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
# Python 斐波那契数列实现
# 获取用户输入数据
nterms = int(input("你需要几项?"))
# 第一和第二项
n1 = 0
n2 = 1
count = 2
# 判断输入的值是否合法
if nterms <= 0:
print("请输入一个正整数。")
elif nterms == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列:")
print(n1, ",", n2, end=" , ")
while count < nterms:
nth = n1 + n2
print(nth, end=" , ")
# 更新值
n1 = n2
n2 = nth
count += 1
插值查找
def binary_search(lis, key):
low = 0
high = len(lis) - 1
time = 0
while low < high:
time += 1
#
mid = low + int((high - low) * (key - lis[low]) / (lis[high] - lis[low]))
print("mid=%s, low=%s, high=%s" % (mid, low, high))
if key < lis[mid]:
high = mid - 1
elif key > lis[mid]:
low = mid + 1
else:
#
print("times: %s" % time)
return mid
print("times: %s" % time)
return False
LIST = [1, 5, 7, 8, 22, 54, 99, 123, 200, 222, 444]
result = binary_search(LIST, 444)
print(result)
代码仅供参考,禁止抄袭