生成有序数组
import numpy as np
numbers = sorted(list(np.random.randint(1,200,size=30))) #生成有序数组
print(numbers)
二分查找
numbers = [2, 9, 16, 16, 16, 24, 33, 39, 43, 48, 66, 72, 76, 91, 94, 104, 106, 113, 115, 131, 137, 137, 138, 158, 178, 183, 187, 187, 195, 197]
'''
tarValue:所要查找的目标值
arr:要查询的有序数组
tarValueIndex:所要查找的目标值在有序数组中的索引
'''
def binarySearch(tarValue,arr):
head = 0
tail = len(arr) #定义末尾索引,末尾元素索引为'len(arr)-1',则mid会包括有序数组除首位元素之外的所有元素索引
while tail - head > 1: #定义循环条件
mid = (head + tail)//2
if tarValue < arr[mid]:
tail = mid
elif tarValue > arr[mid]:
head = mid
elif tarValue == arr[mid]:
tarValueIndex = mid
break
else:
if tarValue == arr[head]:
tarValueIndex = head
else:
tarValueIndex = "数组中无目标元素"
return tarValueIndex
binarySearch(197,numbers)