1. 程式人生 > >折半查詢、快速排序

折半查詢、快速排序

折半查詢

迴圈實現

'''
    折半查詢
        迴圈實現
'''


def binarySearch(list, key):
    low = 0
    high = len(list) - 1
    while (low <= high):  # 迴圈法的判斷條件,就是遞迴法的基線條件
        mid = (low + high) // 2
        gess = list[mid]
        if gess > key:
            high = mid - 1
        if gess < key:
            low = mid + 1
if gess == key: return mid return -1 print(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6))

遞迴實現


# 遞迴實現折半查詢
def binarySearch2(list, low, high, key):
    if (low > high):  # 遞迴的基線條件
        return -1
    else:
        mid = (low + high) // 2
        if (list[mid] == key):
            return
mid if (key > list[mid]): return binarySearch2(list, mid + 1, high, key) # 在序列的後半部分查詢 else: return binarySearch2(list, low, mid - 1, key) # 在序列的前半部分查詢 print(binarySearch2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0, 10, 6))

快速排序

開闢新空間儲存中間結果

'''
    快速排序
        遞迴實現,分而治之
            實現1, 開闢新空間儲存中間結果
            實現2, 不開闢多餘空間來儲存中間結果
'''
# 合併陣列 # print([1, 2, 3, 4] + [5, 6, 7, 8]) # 遞迴法快速排序實現1 def qSort(list): if len(list) < 2: # 基線條件,陣列只有一個元素或者沒有元素是,不需要排序,直接返回 return list else: # 需要排序的陣列 pivot = list[0] less = [i for i in list[1:] if i < pivot] greater = [i for i in list[1:] if i > pivot] return qSort(less) + [pivot] + qSort(greater) listA = [40, 30, 20, 25, 60, 10] print(qSort(listA))

快速排序

分而治之的典型演算法,在遞迴過程中要明確基線條件和遞迴條件


# 遞迴法快速排序實現2
def qSort2(list, left, right):
    if left >= right:
        return None
    else:
        bound = getBound(list, left, right)

        qSort2(list, left, bound - 1)  # 對基準值左側進行排序
        qSort2(list, bound + 1, right)  # 對基準值右側進行排序


def getBound(list, left, right):  # 使用雙指標,參考基準值從兩頭開始挑揀元素
    povit = list[left]
    while (left < right):
        while (left < right and list[right] >= povit):
            right -= 1

        list[left] = list[right]
        while (left < right and list[left] <= povit):
            left += 1

        list[right] = list[left]

    list[left] = povit
    return left


print(listA)
qSort2(listA, 0, len(listA) - 1)
print(listA)