正确理解python中二分查找

二分查找的原理:

1:查找的列表和元组是有序的

2:定义一个中间值的标志位,以这个标志位和要查找的元素进行比较

3:中间标志位=查找元素,查找成功

4:中间标志位>查找元素,要找的元素在左边

5:中间标志位<查找元素,要找的元素在右边

 

def binary_search(data_source,find_n):
  mid=int(len(data_source)/2)   (中间标志位)
  if len(data_source)>=1:
    if data_source[mid]>find_n:  (中间元素大于要查找的元素,向左边查找)
      binary_search(data_source[:mid],find_n)
    elif data_source[mid]<find_n:  (中间元素大于要查找的元素,向右边查找)
      binary_search(data_source[mid:],find_n)
    else:
      print("找到了")

 

原文地址:https://www.cnblogs.com/gaoyuxia/p/10271797.html