接下来就是二分查找的代码
- def binary_search(li, val):
- """
- li表示列表,val表示要查找的数
- 二分查找
- :param li:
- :param val:
- :return:
- """
- left = 0
- right = len(li) - 1
- num = 0
- while left <= right: # 说明候选区还有值 一定要等于
- num += 1
- mid = (left + right) // 2
- if li[mid] == val:
- return mid
- elif li[mid] < val: # 说明需要找的值在中间值的右边,区间变为li[mid]--right
- left = mid + 1
- elif li[mid] > val: # 说明需要找的值在中间值的左边,区间变为left--li[mid]
- right = mid - 1
- print(num)
-
-
- li = [1, 2, 3, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
- binary_search(li, 4)