算法@查找
二分查找
目标:有序数组
特点:每一次都使搜索范围缩小一半
1.比中间那个数大,在后半部分查找,反之在前半部分。
2.重复第一步。
3.如果中间为空,则查找失败。
#-*- coding: utf-8 -*-
#@Time : 2021/4/25 16:44
#@Author : HUGBOY
#@File : test.py
#@Software: PyCharm
# arr 升序数组
def BinarySearch(arr, x, start, end):
if end >= start:
mid = int((end + start)/2)
if x == arr[mid]:
return mid
elif x < arr[mid]:
return BinarySearch(arr, x, start, mid-1)
else:
return BinarySearch(arr, x, mid+1, end)
else:
return -1
arr=[-1,5,6,9,56,897,2056,9999,111111111]
result = BinarySearch(arr, 23, 0, len(arr)-1)
print(result)
________________________________________________________
Every good deed you do will someday come back to you.
Love you,love word !