[Python] 二分查找


Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def binary_search(list, item):
low = 0
hight = len(list)-1
while low <= hight:
mid = int((low + hight) / 2)
guess = list[mid]
if guess == item:
return mid
if guess < item:
low = mid + 1
else:
hight = mid - 1
return None
if __name__ == "__main__":
test_list = [1,3,7,9,32,89,100]
print(binary_search(test_list, 100))
def binary_search(list, item): low = 0 hight = len(list)-1 while low <= hight: mid = int((low + hight) / 2) guess = list[mid] if guess == item: return mid if guess < item: low = mid + 1 else: hight = mid - 1 return None if __name__ == "__main__": test_list = [1,3,7,9,32,89,100] print(binary_search(test_list, 100))
def binary_search(list, item):
    low = 0
    hight = len(list)-1
    while low <= hight:
        mid = int((low + hight) / 2)
        guess = list[mid]
        if guess == item:
            return mid
        if guess < item:
            low = mid + 1
        else:
            hight = mid - 1
    return None

if __name__ == "__main__":
    test_list = [1,3,7,9,32,89,100]
    print(binary_search(test_list, 100))

发布者

Avatar photo

常轩

总要做点什么吧!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注