1. 程式人生 > >Python——二分法

Python——二分法

list = [1,2,4,6,12,34,42,56,66,73,85]

key = 4

center = int(len(list)/2)

if key in list:
    while True:
        if list[center] > key:
            center = center - 1
        elif list[center] < key:
            center = center + 1
        elif list[center] == key:
            print("要找的數字是%d索引是%d"%(key,center))
            break