算法學習:二分法
說明:
函數binary_search接受一個有序數組和一個元素,如果指定的元素包含在數組中,這個函數將返回其位置。開始時查找整個數組,每次檢查中間的元素,如果猜的數小了,對應修改low;如果猜的數大了,對應修改high。
代碼:
1 def binary_search(list1,item): 2 low = 0 3 high = len(list1)-1 4 5 while low <= high: #只要范圍沒有縮小到只包含一個元素 6 mid = (low+high)//2 #檢查中間元素 7 guess = list1[mid] 8 if guess == item: 9 return mid #返回索引 10 if guess > item: 11 high = mid -1 12 if guess < item: 13 low = mid + 1 14 15 return None 16 17 my_list = [1,3,5,7,9] 18 19 print(binary_search(my_list,7)) 20 print(binary_search(my_list,3)) 21 print(binary_search(my_list,-1))
結果:
3
1
None
浙公網安備 33010602011771號