Binary Search Binary Search

Binary Search Binary Search

Binary search algorithm

Binary search (Binary Search) method, is a way to find a given key in the ordered set. Suppose there is a set of key elements of the collection in accordance with the order from small to large. Key elements in the collection can be a list of \ (list = (x_1, x_2 , ..., x_n) \) , where \ (x_i \ Leq + X_ {I}. 1 \) . Task is to find a key \ (key \) position in this list.
For example, \ (List = (-. 5,. 4,. 8, 9,. 19, 81, 195, 803) \) , to find the \ (9 \) is the first few numbers in the list.
If \ (key \) in the list, the report (key \) \ position, otherwise the report lookup fails. If \ (key \) appears more than once in the list (necessarily adjacent), the position of any of the first occurrence is returned.
Binary search method is also called binary search method, the method first comparison \ (Key \) and a list of the middle position \ (MID \) corresponding to the key element, if \ (Key \) and (MID \) \ equal element position, returns \ (MID \) . If \ (Key \) is greater than \ (MID \)Element position, then continue to look at the list of scripts right half of the list, otherwise I keep looking in the left half of the list, the length of the list until the child is 0.
The list of assumptions with \ (L \) represents a length of \ (N \) , the method may be summarized as follows:

  1. 初始化:\(low \leftarrow 0\), \(high \leftarrow N\)
  2. If \ (Low \ geq High \) , the lookup fails, the algorithm ends
  3. 计算 \(mid \leftarrow \lfloor (low + high)/2 \rfloor\)
  4. If \ (L [MID] == Key \) , returns \ (MID \) , the algorithm ends
  5. If \ (L [MID]> Key \) , then \ (High \ LeftArrow MID \) , go to step 2
  6. If \ (L [MID] <Key \) , then \ (Low \ rightarrow MID. 1 + \) , go to step 2

python achieve

Using the binary search method is a divide and conquer strategy, the solution is not to reduce the search space, you can use recursive manner, can also be implemented in a circular fashion.
If a recursive manner, recursive sequence length of the baseline condition is to be searched is zero. Each recursive, the difference in comparison with the sequence key intermediate element, according to the comparison result, it is equal, otherwise the search continues recursively subsequence.

def binary_search_r(lst, key, low=0, high=None):
    """
    在有序列表lst中查找key,递归实现
    @lst: 有序列表
    @key: 查找的键
    """
    if high is None:
        high = len(lst)
    if low >= high: # 基线条件
        return None
    mid = (low + high) // 2
    if key == lst[mid]: # 查找成功
        return mid
    elif key < lst[mid]:
        high = mid # 左子序列递归查找
        return binary_search_r(lst, key, low, high)
    else:
        low = mid + 1 # 右子序列查找
        return binary_search_r(lst, key, low, high)

If the cycle realization, is recorded in the cycle of the current search \ (Low \) , \ (High \) two positions, depending on the size of the key elements of intermediate sequence comparison result, either the search is successful, or change \ (Low \) or (high \) \ values until \ (Low \ geq High \) .

def binary_search(lst, key):
    """
    在有序列表lst中查找key,循环实现
    @lst: 有序列表
    @key: 查找的键
    """
    low = 0
    high = len(lst)
    while low < high:
        mid = (low + high) // 2
        if key == lst[mid]:
            return mid
        elif key < lst[mid]:
            high = mid
        else:
            low = mid + 1
    return None

Here is a simple test code:

if __name__ == "__main__":
    x = [3, 5, 6, 7, 9, 100, 107]
    for ax in x:
        print(ax, binary_search_r(x, ax), binary_search(x, ax))
    for ax in [-5, -1, 0, 10, 105, 123]:
        print(ax, binary_search_r(x, ax), binary_search(x, ax))

Binary search algorithm analysis

  • The correctness of
    each iteration of binary search, will find the range is limited to \ (low \) and \ (high \) between, which is considered \ (key \) if there \ (L \) , you must there \ (L [Low] \ Leq Key <L [High] \) . So to correct the algorithm, as long as this statement is true: If \ (Key \ in L \) , then at each iteration, \ (L [Low] \ Leq Key <L [High] \) necessarily true.

  • Initialization, \ (0 = Low, High = N \) , established proposition.
  • In the assumed \ (K \) step statement is true, then the \ (L [low_k] \ Leq Key <L [high_k] \) .
  • In the \ (k + 1 \) step, \ (MID = \ lfloor (low_k high_k +) / 2 \ rfloor \) :

    • If \ (Key> L [MID] \) , then \ (Key \) satisfies $ L [mid] <key < L [high_k] $. The new subinterval taken \ (the I = [L [MID], L [high_k]) \) , there must be \ (Key \ in the I \) ;
    • If \ (Key <L [MID] \) , then \ (Key \) satisfies $ L [low_k] <key < L [mid] $. The new sub-subinterval taken \ (the I = [L [low_k], L [MID]) \) , then \ (Key \ in the I \) ;
    • If \ (Key = L [MID] \) , then find success.
  • time complexity

    The worst case, the key is not in the list, but the binary search until the final sequence of length 0 stopped. Suppose the original sequence of length \ (N \) , each iteration will range by half. After the first iteration, the sequence length of unknown origin \ (N / 2 \) , after the second iteration, the sequence length of unknown origin \ (N / 2 ^ 2 \) . Maximum number of iterations is set to \ (K \) , then \ (N / 2 ^ {K-. 1}>. 1, N / 2 ^ {K} \ Leq. 1 \) , i.e. \ (k = \ lceil \ log_2 N \ rceil \) . Thus, the length of \ (N \) of the table, the maximum number of iterations of the binary search \ (\ log_2 N \) , the algorithm complexity is \ (O (\ log_2N) \) .

Guess you like

Origin www.cnblogs.com/data_algorithms/p/binary_search.html