python实现搜索最小值,顺序搜索,二叉树搜索,算法复杂度依次为O(n),O(n),O(log2 n)。
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:
midpoint = (left+right)//2
if target == sortedLyst[midpoint]:
return midpoint
elif target < sortedLyst[midpoint]:
right = midpoint - 1
else:
left = midpoint + 1
return -1
def main():
lyst = [1,2,6,43,2,76,-4,43,326,46]
index = indexOfMin(lyst)
print(index)
if __name__ == "__main__":
main()