軟件環境:Python 3.7.0b4
一、分而治之
工作原理:
- 找出簡單的基線條件;
- 確定如何縮小問題的規模,使其符合基線條件。
# 4.2 def count(list): if list == []: return 0 return 1 + count(list[1:]) # 4.3 def max(list): if len(list) == 2: return list[0] if list[0] > list[1] else list[1] sub_max = max(list[1:]) return list[0] if list[0] > sub_max else sub_max
4.4:二分查找的基線條件是數組只包含一個元素。如果要查找的值與這個元素相同,就找到了!否則說明它不在數組中。遞歸條件為 把數組分成兩半,將其中一半丟棄,並對另一半執行二分查找。
二、快速排序
def quicksort(array): if len(array) < 2: # 基線條件:為空或只包含一個元素的數組是“有序”的 return array else: # 遞歸條件 pivot = array[0] # 由所有小於等於基准值的元素組成的子數組 less = [i for i in array[1:] if i <= pivot] # 由所有大於基准值的元素組成的子數組 greater = [i for i in array[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) print(quicksort([10, 5, 2, 3])) # 需排序的數組
三、小結
- 分治法是將問題逐步分解。使用分治法處理列表時,基線條件很可能是空數組或只包含一個元素的數組。
- 實現快速排序時,請隨機地選擇用作基准值的元素。快速排序的平均運行時間為O(nlog n)。