Skip to content

Commit 6534d02

Browse files
committed
learn merge sort
1 parent d3773de commit 6534d02

File tree

5 files changed

+87
-1
lines changed

5 files changed

+87
-1
lines changed
263 KB
Loading
13.1 KB
Loading

sorts/merge_sort/merge_sort.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
# Created by imoyao at 2019/5/13 18:33
4+
5+
import pathlib
6+
import sys
7+
8+
util_p = pathlib.Path('../..').resolve()
9+
10+
sys.path.append(str(util_p))
11+
from util import utils
12+
13+
14+
def merge_sorted_col(left_col, right_col):
15+
"""
16+
对两个已排序序列进行归并
17+
:param left_col:
18+
:param right_col:
19+
:return: 归并之后的序列
20+
"""
21+
sorted_col = list()
22+
while left_col and right_col:
23+
'''
24+
注意此处pop()操作,将两个序列中小的元素直接append到最终列表中。
25+
>>> a = list(range(5))
26+
>>> a
27+
[0, 1, 2, 3, 4]
28+
>>> a.pop(0)
29+
0
30+
>>> a
31+
[1, 2, 3, 4]
32+
'''
33+
sorted_col.append(left_col.pop(0) if left_col[0] <= right_col[0] else right_col.pop(0))
34+
# 最终将长的列表剩余元素和已排序的列表连接起来
35+
return sorted_col + left_col + right_col
36+
37+
38+
def merge_sort(unsorted_collection):
39+
"""
40+
归并排序
41+
:param unsorted_collection:待排序序列
42+
:return:排序后序列
43+
"""
44+
length = len(unsorted_collection)
45+
if length <= 1:
46+
return unsorted_collection
47+
mid_index = length // 2 # 从中间分割
48+
left_col = unsorted_collection[:mid_index]
49+
right_col = unsorted_collection[mid_index:]
50+
# 注意merge_sorted_col内部使用递归对左右两边继续进行排序
51+
sorted_col = merge_sorted_col(merge_sort(left_col), merge_sort(right_col)) # 调用合并方法,将左右两边排序过的序列合并
52+
return sorted_col
53+
54+
55+
if __name__ == '__main__':
56+
unsorted_li = utils.rand_list(100)
57+
print('Before sorted:', unsorted_li)
58+
print('After sorted:', merge_sort(unsorted_li))

sorts/merge_sort/readme.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# 归并排序
2+
3+
## 概念
4+
5+
归并排序(Merge sort 或 mergesort),是创建在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用,且各层分治递归可以同时进行。
6+
7+
## 原理
8+
9+
归并排序算法的运作如下:
10+
11+
**分解**:将待排序的 `n` 个元素分成各包含 `n/2` 个元素的子序列
12+
**解决**:使用归并排序递归排序两个子序列
13+
**合并**:合并两个已经排序的子序列以产生已排序的答案
14+
15+
## 图示
16+
17+
![归并排序算法](./img/Merge_sort_animation.gif)
18+
19+
![归并排序实例](./img/Merge-sort-example.gif)
20+
21+
## 复杂度
22+
23+
平均时间复杂度:`O(nlogn)`

sorts/readme.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,15 @@
33
**注意**:在排序算法中,我们默认讨论的序列内部元素是可比较的,否则无意义。
44

55
- [选择排序](./selection_sort)
6-
- [快速排序](./quick_sort)
76
- [冒泡排序](./bubble_sort)
87
- [插入排序](./insertion_sort)
98
- [希尔排序](./shell_sort)
9+
<details>
10+
<summary><mark><font color=darkred>- 高级排序算法</font></mark></summary>
11+
- [快速排序](./quick_sort)
12+
- [归并排序](./merge_sort)
13+
</details>
14+
1015

1116

1217

0 commit comments

Comments
 (0)