[算法01] Binary Search

Binary Search二分查找

做用:二分查找適用於有序的的數組或列表中,若是列表及數組中有n個元素,經過二分查找查詢某一元素的位置須要的步驟是log(n)(注:該log的底數是2);python

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

注意事項函數

  1. python定義的函數、使用如if、while、for時在語句後使用分號';'
  2. 列表元素索引從0開始;
  3. 若是定義的函數具備返回值,那麼返回值經過關鍵字'return'實現函數輸出,可多輸出,若是調用函數返回值,可經過查詢對應返回值索引,查找所需的函數返回值;
  4. 求中間索引位置時,防止出現查詢調用時索引計算出現小數,經過round函數進行四捨五入處理;

Matlab實現

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

  1. Matlab數組元素索引從1開始,這點與python不一樣;
  2. 函數返回值在定義函數時直接定義;
相關文章
相關標籤/搜索