Implementation of Python binary search (half search)

time complexity

Optimal Time Complexity: O(1) 
Worst Time Complexity: O(logn)

train of thought

Search the ordered sequence table , search by subscript, take half of the search each time, such as [1,2,3,4,5,6,7,8,9], check 3, subscript from 0~8, (0+8)//2=4, compare half to the element 3 with subscript 2, 3<5, the 3 to be checked is on the left of 5, and then continue in the same way

Find element 4, the subscript is 2: the subscript of the list is from 0-8, so the half subscript is (0+8)//2=4, the subscript 2 of the element 4 to be searched is less than the half subscript 4 element 7, so element 4 is on the left side of element 7, and then continue to double and repeat the search

 

Code

1. Non-recursive implementation

def binary_search(alist, item):
    """二分查找:非递归实现"""
    first = 0
    last = len(alist) - 1
    while first <= last:
        midpoint = (first + last) // 2
        if alist[midpoint] == item:
            return True
        elif item < alist[midpoint]:
            last = midpoint - 1
        else:
            first = midpoint + 1
    return False


testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search(testlist, 3))  # 返回False,未查找到
print(binary_search(testlist, 13))  # 返回True,查找到了

2. Recursive implementation

def binary_search_2(alist, item):
    """二分查找:递归实现"""
    if len(alist) == 0:
        return False
    else:
        midpoint = len(alist)//2
        if alist[midpoint] == item:
          return True
        else:
          if item<alist[midpoint]:
            return binary_search(alist[:midpoint],item)
          else:
            return binary_search(alist[midpoint+1:],item)


testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binary_search_2(testlist, 3))  # 返回False,未查找到
print(binary_search_2(testlist, 13))  # 返回True,查找到了

Guess you like

Origin blog.csdn.net/qq_37140721/article/details/130318278