《算法图解》第一章 算法简介之python 二分查找

python 二分查找

def binary_search(lst, item):
	low=0
	high = len(lst)-1
	while low <= high:
		mid = (low + high)/2
		guess = lst[mid]
		if guess == item:
			return mid
		if guess > item:
			high = mid- 1
		else:
			low=mid+1
	return None
my_list=[1,3,5,7,9]
print(binary_search(my_ list, 3)) # => 1
print(binary_search(my_ list, -1)) # => None

小结

  • 二分查找的速度比简单查找快得多。

  • O(log n)比O(n)快。需要搜索的元素越多,前者比后者就快得越多。

  • 算法运行时间并不以秒为单位。

  • 算法运行时间是从其增速的角度度量的。

  • 算法运行时间用大O表示法表示。

posted @ 2022-11-13 22:35  dlhl  阅读(14)  评论(0)    收藏  举报