1.二分查找(元素有序,相邻存放-顺序表)
import sys
sys.setrecursionlimit(100000)
def binary_search_re(A, item):
n = len(A)
if n >= 1:
mid = n//2
if A[mid] == item:
return True
elif item < A[mid]:
return binary_search_re(A[:mid], item)
else:
return binary_search_re(A[mid+1:], item)
return False
def binary_search_nore(A, item):
n = len(A)
first = 0
last = n-1
while first <= last:
mid = (first + last)//2
if A[mid] == item:
return True
elif item < A[mid]:
last = mid - 1
else:
first = mid + 1
return False
if __name__ == '__main__':
li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
print(binary_search_re(li, 55))
print(binary_search_re(li, 70))
print(binary_search_nore(li, 55))
print(binary_search_nore(li, 70))