二分查找——Python实现

时间:2022-04-10 04:54:14

一、排序思想

二分(折半)查找思想请参见:https://www.cnblogs.com/luomeng/p/10585291.html

二、python实现

def binarySearchDemo(arr, key):
"""
python二分查找非递归方式
:param arr:待排序列,有序集合
:param key:带查找元素
"""
low = 0
high = len(arr) - 1 while low <= high:
mid = (low + high) // 2 if key > arr[mid]:
low = mid + 1
elif key < arr[mid]:
high = mid - 1
else:
return mid
return -1 def binarySearchDemo2(arr, start, end, key):
"""
python二分查找递归方式
:param arr:待排序列,有序集合
:param start:待排序列,开始位置
:param end:待排序列,结束位置
:param key:带查找元素
"""
if start > end:
return -1 mid = (start + end) // 2 if key > arr[mid]:
return binarySearchDemo2(arr, mid + 1, end, key)
elif key < arr[mid]:
return binarySearchDemo2(arr, start, mid - 1, key)
else:
return mid nums = [6, 12, 33, 87, 90, 97, 108, 561] # 非递归实现
print(binarySearchDemo(nums, 90)) # 递归实现
print(binarySearchDemo2(nums, 0, len(nums) - 1, 90))