歸併排序的核心思想是分治,基礎演算法是遞迴。想要學好分治,遞迴必須熟練。
具體思想就不講了,貼出python實現的**(其中加了print來顯示計算過程):
def _merge_sorted(nums):
# print("nums is :" + str(nums))
if(len(nums) <= 1):
return nums
m = len(nums)//2
# print("m is:" + str(m))
a = _merge_sorted(nums[:m])
b = _merge_sorted(nums[m:])
return merge(a, b)
def merge(a, b):
temp =
i = 0
j = 0
while (i < len(a) and j < len(b)):
if(a[i] < b[j]):
i += 1
else:
j += 1
if(i < len(a)):
temp = temp + a[i:]
if(j < len(b)):
temp = temp + b[j:]
# print("a is: " + str(a))
# print("b is: " + str(b))
# print("temp is:" + str(temp))
return temp
li = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
_merge_sorted(li)
nums is :[1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
m is:5
nums is :[1, 3, 5, 7, 9]
m is:2
nums is :[1, 3]
m is:1
nums is :[1]
nums is :[3]
a is: [1]
b is: [3]
temp is:[1, 3]
nums is :[5, 7, 9]
m is:1
nums is :[5]
nums is :[7, 9]
m is:1
nums is :[7]
nums is :[9]
a is: [7]
b is: [9]
temp is:[7, 9]
a is: [5]
b is: [7, 9]
temp is:[5, 7, 9]
a is: [1, 3]
b is: [5, 7, 9]
temp is:[1, 3, 5, 7, 9]
nums is :[2, 4, 6, 8, 0]
m is:2
nums is :[2, 4]
m is:1
nums is :[2]
nums is :[4]
a is: [2]
b is: [4]
temp is:[2, 4]
nums is :[6, 8, 0]
m is:1
nums is :[6]
nums is :[8, 0]
m is:1
nums is :[8]
nums is :[0]
a is: [8]
b is: [0]
temp is:[0, 8]
a is: [6]
b is: [0, 8]
temp is:[0, 6, 8]
a is: [2, 4]
b is: [0, 6, 8]
temp is:[0, 2, 4, 6, 8]
a is: [1, 3, 5, 7, 9]
b is: [0, 2, 4, 6, 8]
temp is:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
歸併演算法 歸併排序
歸併演算法 歸併排序 這周需要用到歸併演算法,於是找了找相關的資料,整理如下 歸併排序 merge sort 是利用 歸併 技術來進行排序。歸併是指將若干個已排序的子檔案合併成乙個有序的檔案。兩路歸併演算法 1 演算法基本思路 設兩個有序的子檔案 相當於輸入堆 放在同一向量中相鄰的位置上 r low...
歸併排序演算法
include stdafx.h include include include 合併兩段已經排好序的列表 void merge int list int mergelist int left int mid int right else if i mid else 將列表list按照seglen分...
歸併排序演算法
這個演算法感覺比插入難理解一些,下面說說我的理解 歸併排序的步驟 1.把長度為n的序列分為兩個長度為n 2的子串行 2.對這兩個子串行分別採用歸併排序 3.將兩個子串行合併成乙個最終的排序序列 通過步驟2可看到 在歸併排序中又用了歸併排序,可見這是乙個遞迴的過程。例如乙個陣列 a 8 下面採用遞迴排...