做用:二分查找適用於有序的的數組或列表中,若是列表及數組中有n個元素,經過二分查找查詢某一元素的位置須要的步驟是log(n)(注:該log的底數是2);python
def binary_search(list,item): low = 0 high = len(list)-1 #python數組ID從0開始,與matlab不一樣、 t = 0 while low <= high: t = t + 1; mid = round((low + high)/2) guess = list[mid] if guess == item: return (mid,t) if guess > item: high = mid-1 else: low = mid + 1 return None #python關鍵字None,至關於matlab的NaN my_list = range(1,101) value = binary_search(my_list,1) print ("Search Num:",value[1],'Index Position',value[0])
運行後結果:數組
Search Num: 6 Index Position 0
注意事項函數
function [count,out] = binary_search(list,item) %list:所要查找的數組一維行向量 %item:查找的元素 low = 1; high = length(list); t = 0; while low <= high t = t+1; mid = round((low+high)/2); guess = list(1,mid); if guess == item out = mid; count = t; break; else if guess > item high = mid - 1; if high<low out = 'None'; break; end else low = mid + 1; if high<low out = 'None'; break; end end end end
注意事項code