實作二分搜尋
在這支影片裡,你學會如何實作 linear search 與 binary search,也看到了它們之間的差異。
在這個練習中,你需要實作 binary_search() 函式。你做得到嗎?
本練習屬於課程
Data Structures and Algorithms in Python
練習說明
- 檢查搜尋值是否等於中間位置的值。
- 檢查搜尋值是否小於中間位置的值。
- 將
last設為middle減一的值。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def binary_search(ordered_list, search_value):
first = 0
last = len(ordered_list) - 1
while first <= last:
middle = (first + last)//2
# Check whether the search value equals the value in the middle
if ____ == ____:
return True
# Check whether the search value is smaller than the value in the middle
elif ____ < ____:
# Set last to the value of middle minus one
____
else:
first = middle + 1
return False
print(binary_search([1,5,8,9,15,20,70,72], 5))