def
merge
(left, right):
"""歸併兩個陣列
:param left: 第乙個陣列
:param right: 第二個陣列
:return: 歸併後的有序的的陣列
"""print("left", left)
print("right", right)
i, j = 0, 0
n1, n2 = len(left), len(right)
r =
while i < n1 and j < n2:
while i < n1:
if j == n2:
break
if left[i] <= right[j]:
else:
break
i += 1
while j < n2:
if i == n1:
break
if right[j] <= left[i]:
else:
break
j += 1
r.extend(left[i:])
r.extend(right[j:])
return r
defmerge_sort
(a):
""" 使用遞迴來完成歸併
:param a: 要排序的陣列
:return: 返回值為排好序的陣列
"""if len(a) == 1:
return a
mid = len(a) >> 1
left = merge_sort(a[:mid]) # 給左邊排序
right = merge_sort(a[mid:]) # 給右邊排序
return merge(left, right)
if __name__ == "__main__":
a = [10, 2, 3, 6, 8, 1, 10, 100, 200, 6] # , 3, 10, 4, 3, 10, 10, 4, 3, 10]
print(a)
b = merge_sort(a)
print(b)
python實現歸併排序
歸併排序,先把陣列按中間分為2個單元,直至每個單元僅包含1個元素,然後依次合併2個單元至一臨時陣列 def merge str,start index,end index,mid,temp j start index k mid 1 i 0while j mid and k end index if...
Python實現歸併排序
def mergesort seq if len seq 1 return seq else mid int len seq 2 lpart mergesort seq mid rpart mergesort seq mid return merge lpart,rpart defmerge lpa...
Python實現歸併排序
歸併排序是典型的分治法的應用 思想 先遞迴分解陣列,再合併陣列 原理 將陣列分解最小之後,然後合併兩個有序陣列,基本思想是比較兩個陣列的最前面的數,誰小就取誰,取完後,將相應的指標後移以為。然後再比較,直到乙個陣列為空,最後把另乙個陣列的剩餘部分複製過來即可。python 實現 歸併排序 def m...