# 踏踏实实地打好算法基础(F)—归并排序(Merge Sort)

### 基本思想

• 将序列中待排序数字分为若干组，每个数字分为一个组
• 将若干个组两两合并，保证合并后的组是有序的
• 重复第二步操作直到只剩下一组，排序完成

### 合并两个序列

#### 代码实现

``````def merge_two_sorted_lists(a,b):
sorted_list = []

return sorted_list

if __name__ == '__main__':
a = [5,8,12,56]
b = [7,9,45,51]

print(merge_two_sorted_lists(a,b))

``````def merge_two_sorted_lists(a,b):
sorted_list = []
len_a = len(a)
len_b = len(b)

i = j = 0

while i < len_a and j < len_b:
if a[i] <= b[j]:
sorted_list.append(a[i])
i += 1
else:
sorted_list.append(b[j])
j += 1
while i < len_a:
sorted_list.append(a[i])
i += 1
while j < len_b:
sorted_list.append(b[j])
j += 1

return sorted_list

if __name__ == '__main__':
a = [5,8,12,56]
b = [7,9,45,51]

print(merge_two_sorted_lists(a,b))

``````    while i < len_a:
sorted_list.append(a[i])
i += 1
while j < len_b:
sorted_list.append(b[j])
j += 1

#### 划分序列

``````def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]

left = merge_sort(left)
right = merge_sort(right)

return merge_two_sorted_lists(left,right)

``````def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]

left = merge_sort(left)
right = merge_sort(right)

return merge_two_sorted_lists(left,right)

def merge_two_sorted_lists(a,b):
sorted_list = []
len_a = len(a)
len_b = len(b)

i = j = 0

while i < len_a and j < len_b:
if a[i] <= b[j]:
sorted_list.append(a[i])
i += 1
else:
sorted_list.append(b[j])
j += 1
while i < len_a:
sorted_list.append(a[i])
i += 1
while j < len_b:
sorted_list.append(b[j])
j += 1

return sorted_list

if __name__ == '__main__':
a = [5,8,12,56]
b = [7,9,45,51]

arr = [5,8,12,56,7,9,45,51]

print(merge_sort(arr))

``````def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]

# left = merge_sort(left)
# right = merge_sort(right)
merge_sort(left)
merge_sort(right)

return merge_two_sorted_lists(left,right,arr)

def merge_two_sorted_lists(a,b,arr):
# sorted_list = []
len_a = len(a)
len_b = len(b)

i = j = k = 0

while i < len_a and j < len_b:
if a[i] <= b[j]:
arr[k] = a[i]
# sorted_list.append(a[i])
i += 1
else:
arr[k] = b[j]
# sorted_list.append(b[j])
j += 1
k+=1
while i < len_a:
# sorted_list.append(a[i])
arr[k] = a[i]
i += 1
k += 1
while j < len_b:
arr[k] = b[j]
# sorted_list.append(b[j])
j += 1
k += 1

# return sorted_list

if __name__ == '__main__':
a = [5,8,12,56]
b = [7,9,45,51]

arr = [5,8,12,56,7,9,45,51]
merge_sort(arr)
print(arr)