python常见查找方法实现

1.二分查找(元素有序,相邻存放-顺序表)

#RecursionError: maximum recursion depth exceeded in comparison 超过最大递归深度,需要调的大一点
import sys
sys.setrecursionlimit(100000) #调整最大递归深度
def binary_search_re(A, item):
    n = len(A)
    if n >= 1: #有元素的情况下
        mid = n//2
        if A[mid] == item:
            return True
        elif item < A[mid]:#左边
            return binary_search_re(A[:mid], item)
        else:#右边
            return binary_search_re(A[mid+1:], item)
    return False

def binary_search_nore(A, item):
    n = len(A)
    first = 0
    last = n-1
    while first <= last:
        mid = (first + last)//2
        if A[mid] == item:
            return True
        elif item < A[mid]:#左边
            last = mid - 1
        else:
            first = mid + 1
    return False




if __name__ == '__main__':
    li = [17, 20, 26, 31, 44, 54, 55, 77, 93]

    #递归版本
    print(binary_search_re(li, 55))
    print(binary_search_re(li, 70))

    #非递归版本
    print(binary_search_nore(li, 55))
    print(binary_search_nore(li, 70))

猜你喜欢

转载自blog.csdn.net/hot7732788/article/details/89220095