1. 程式人生 > >演算法第四版----python實現

演算法第四版----python實現

二分查詢

def BinarySearch(tinyT,tinyW):
    tinyW.sort()
    for i in range(0,len(tinyT)):
        length_start = 0
        length_end = len(tinyW) - 1
        while length_start <= length_end:
            mid = length_start + (length_end - length_start) //2
            if length_end != length_start:
                if tinyT[i] < tinyW[mid]:
                    length_end = mid - 1
                elif tinyT[i] > tinyW[mid]:
                    length_start = mid + 1
                else:
                    break
            else:
                length_start = 1
                length_end = 0
                if tinyT[i] != tinyW[mid]:
                    print(tinyT[i])
if __name__ == '__main__':
    tinyT = [23,50,10,99,18,23,98,84,11,10,48,77,13,54,98,77,77,68]     # 比較list
    tinyW = [84,48,68,10,18,98,12,23,54,57,33,16,77,11,29]              # 原始list
    BinarySearch(tinyT,tinyW)