1. 程式人生 > >二分查詢-Binary search

二分查詢-Binary search

二分查詢

WIKI

In computer science, binary search, also known as half-interval search,[1] logarithmic search,[2] or binary chop,[3] is a search algorithm that finds the position of a target value within a sorted array.

簡單查詢VS二分查詢

簡單查詢:從頭開始查詢

二分查詢:二分查詢就是將查詢的鍵和子陣列的中間鍵作比較,如果被查詢的鍵小於中間鍵,就在左子陣列繼續查詢;如果大於中間鍵,就在右子陣列中查詢,否則中間鍵就是要找的元素。

簡單查詢

二分查詢

複雜度

O(n)

O(logn)

二分查詢複雜度參考文獻:

Python程式碼

"""

Input:list,item

Output:index of item

"""





def binary_search(alist, aitem):

    low = 0

    high = len(alist) - 1

    while low <= high:

        mid = (low + high) / 2

        guess = alist[mid]

        if guess == aitem:

            return mid

        if guess > aitem:

            high -= 1

        else:

            low += 1

    return None





if __name__ == "__main__":

    alist = [1, 3, 5, 7, 8]

    aitem = 3

    aindex = binary_search(alist, aitem)