我見過這種算法的很多不同的實現,但我想知道是否有辦法提高效率,而不僅僅是製作搜索二進制文件。我已經設計了算法的這個特定版本,因此,將立即檢查數組/列表的邊緣和中點以便搜索關鍵字,以避免在您尋找的關鍵字只是第一個,中間時循環搜索或最後一個元素。這個遞歸二分法搜索算法可以更有效嗎?
def searchRB(the_array, the_key, imin, imax):
print("searching")
found = False
if (0 > the_key or the_key > len(the_array)):
return found
else:
imid = imin + ((imax - imin) // 2)
if imid == the_key or imin == the_key or imax == the_key:
found = True
return found
elif the_array[imid] > the_key:
return searchRB(the_array, the_key, imin, imid-1)
elif the_array[imid] < the_key:
return searchRB(the_array, the_key, imid+1, imax)
else:
return found
例如,如果您正在尋找在1-100一個列表中的號碼1,這將找到它的第一個循環,不像其他一些實現。
但是,我不確定這是否實際上提高了效率(除了某些邊緣情況),並且如果在繼續循環時檢查list/array中的第一個,中間和最終值實際上是有害的並且每次都必須檢查這三個值。
這是這種算法的好壞實施,還是我只是分裂頭髮?
迭代二進制搜索將更有效。 – keshlam
有趣的是,你能否詳述一下爲什麼是這樣? – 123
你將如何開始搜索? the_key,imin,imax的值是什麼? – LetzerWille