您好,登錄后才能下訂單哦!
搜索常見算法:順序查找,二分法查找,哈希查找,下面是二分查找的實(shí)現(xiàn)方式
# coding:utf-8
# 二分查找的前提:只能對有序列進(jìn)行查找
def binary_search(alist,item):
"""二分查找---遞歸實(shí)現(xiàn)"""
n = len(alist)
if n > 0:
mid = n//2
if item == alist[mid] :
return True
elif item < alist[mid]:
return binary_search(alist[:mid],item)
else:
return binary_search(alist[mid+1:], item)
else :
return False
def binary_search_2(alist,item):
"""二分查找---非遞歸版本"""
n = len(alist)
first = 0
last = n-1
while first <= last:
mid = (first + last)//2
if alist[mid] ==item:
return True,mid
elif item < alist[mid]:
last = mid - 1
else:
first = mid + 1
return False
if __name__ == "__main__":
a = [1,5,6,10,11,13,18,37,99]
print(a)
sorted_list_11 = binary_search(a,1)
print(sorted_list_11)
sorted_list_12= binary_search(a, 88)
print(sorted_list_12)
sorted_list_21 = binary_search_2(a, 18)
print(sorted_list_21)
sorted_list_22 = binary_search_2(a, 88)
print(sorted_list_22)
# [1, 5, 6, 10, 11, 13, 18, 37, 99]
# True
# False
# (True, 6)
# False
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。