演算法導論—歸併排序python實現
阿新 • • 發佈:2018-12-19
Suppose we have two piles of cards face up on a table. Each pile is sorted, with the smallest cards on top. We wish to merge the two piles into a single sorted output pile, which is to be face down on th table. Our basic step consists of choosing the smaller of the two cards on top of the face-up piles, removing it from its pile(which exposes a new top card), and placing this card face down onto the output pile. We repeat this step until one input pile is empty.
假設有兩堆已經排好的牌,現在我們要將他們合併成一堆,那麼只需要在每一堆設定一個標兵,那個標兵表示的數小就把這個數存到我們所需的數組裡面,之後標兵會後退一步,直到整個迭代結束。
這裡首要注意的是,下面這兩句話,此處不解釋,只有單步除錯過才會明白為什麼要這麼寫:
left.append(float("inf")) # 陣列尾以正無窮結束
right.append(float("inf")) # 陣列尾以正無窮結束
# 歸併排序 def merge(arr, p, q, r): left = [] right = [] for i in range(p, q + 1): left.append(arr[i]) for j in range(q + 1, r + 1): right.append(arr[j]) left.append(float("inf")) right.append(float("inf")) i = 0 j = 0 for k in range(p, r + 1): if left[i] <= right[j]: arr[k] = left[i] i = i + 1 else: arr[k] = right[j] j = j + 1 def merge_sort(arr, p, r): if p < r: q = (p + r) // 2 merge_sort(arr, p, q) merge_sort(arr, q + 1, r) merge(arr, p, q, r) array = [4, 3, 2, -7, -1, 6, 3, 10] merge_sort(array, 0, len(array) - 1) print(array)