文章目录
第3章 搜索、排序和复杂度分析
搜索算法
搜索最小值
def indexOfMin(lyst):
minIndex = 0
currentIndex = 1
while currentIndex < len(lyst):
if lyst[currentIndex] < lyst[minIndex]:
minIndex = currentIndex
currentIndex += 1
return minIndex
顺序搜索列表
def sequentialSearch(target, lyst):
position = 0
while position < len(lyst):
if target == lyst(position):
return position
position += 1
return -1
有序列表的二叉搜索
def binarySearch(target, sortedLyst):
left = 0
right = len(sortedLyst) - 1
while left <= right:
mid = (left + right) // 2
if target == sortedLyst(mid):
return mid
elif target < sortedLyst(mid):
right = mid