1. 程式人生 > >python中二分查詢

python中二分查詢

二分查詢也稱折半查詢,它的效率較高。但是二分查詢要求線性表必須採用順序儲存結構,而且表中元素按關鍵字有序排列。

寫二分查詢時有兩個方法,一個是用遞迴,一個不用遞迴。

用遞迴的方法如下

#coding:utf-8

def binary_search(alist,item):
    """二分查詢。遞迴法"""
    n = len(alist)
    if n > 0:
        mid = n//2
        if alist[mid] == item:
            return True
        elif alist[mid] > item:
            return binary_search(alist[:mid],item)
        else:
            return binary_search(alist[mid+1:],item)
    return False


if __name__ == "__main__":

    li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
    print(binary_search(li,55))
    print(binary_search(li,521))

不用遞迴的方法寫法如下

#coding:utf-8

def binary_search_2(alist,item):
    """二分查詢。非遞迴方法"""
    n = len(alist)
    first = 0
    last = n-1

    while first <= last:
        mid = (first + last) // 2
        if alist[mid] ==item:
            return True
        elif alist[mid] < item:
            first = mid+1
        else:
            last = mid-1
    return False

if __name__ == "__main__":

    li = [17, 20, 26, 31, 44, 54, 55, 77, 93]
    print(binary_search_2(li, 55))
    print(binary_search_2(li, 521))    

二分查詢的最優時間複雜度是O(1)

最壞時間複雜度是O(logn)