数据结构:二分查找python实现

二分查找是分而治之策略很好的例子,这里给出了两种实现,其中一种是使用递归方式实现。

#二分法
#递归查找
def Binary_search(alist, item, first, last):
    found = False
    while first <= last and not found:
        mid = (first + last) // 2
        if alist[mid] == item:
            return True
        elif alist[mid] < item:
            last = mid-1
            Binary_search(alist, item, first, last)
        else:
            first = mid+1
            Binary_search(alist, item, first, last)
    return found

def binarySearch(alist, item):
    first = 0
    last = len(alist) - 1
    found = False
    while first <= last and not found:
        mid = (first + last) // 2
        if alist[mid] == item:
            return True
        else:
            if item < alist[mid]:
                last = mid - 1
            else:
                first = mid + 1
    return found
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(Binary_search(testlist, 3, 0, 8))
print(Binary_search(testlist, 13, 0, 8))


print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))

 

你可能感兴趣的:(python编程,数据结构与算法)