Skip to content

Commit cf385ad

Browse files
author
wuyudi
authored
Update merge_sort.py (TheAlgorithms#2356)
* Update merge_sort.py * Update merge_sort.py
1 parent 61dde44 commit cf385ad

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

sorts/merge_sort.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,40 @@
11
"""
22
This is a pure Python implementation of the merge sort algorithm
3-
43
For doctests run following command:
54
python -m doctest -v merge_sort.py
65
or
76
python3 -m doctest -v merge_sort.py
8-
97
For manual testing run:
108
python merge_sort.py
119
"""
1210

1311

14-
def merge_sort(collection):
12+
def merge_sort(collection: list) -> list:
1513
"""Pure implementation of the merge sort algorithm in Python
16-
1714
:param collection: some mutable ordered collection with heterogeneous
1815
comparable items inside
1916
:return: the same collection ordered by ascending
20-
2117
Examples:
2218
>>> merge_sort([0, 5, 3, 2, 2])
2319
[0, 2, 2, 3, 5]
24-
2520
>>> merge_sort([])
2621
[]
27-
2822
>>> merge_sort([-2, -5, -45])
2923
[-45, -5, -2]
3024
"""
3125

32-
def merge(left, right):
26+
def merge(left: list, right: list) -> list:
3327
"""merge left and right
3428
:param left: left collection
3529
:param right: right collection
3630
:return: merge result
3731
"""
38-
result = []
39-
while left and right:
40-
result.append((left if left[0] <= right[0] else right).pop(0))
41-
return result + left + right
32+
def _merge():
33+
while left and right:
34+
yield (left if left[0] <= right[0] else right).pop(0)
35+
yield from left
36+
yield from right
37+
return list(_merge())
4238

4339
if len(collection) <= 1:
4440
return collection
@@ -47,6 +43,8 @@ def merge(left, right):
4743

4844

4945
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()
5048
user_input = input("Enter numbers separated by a comma:\n").strip()
5149
unsorted = [int(item) for item in user_input.split(",")]
5250
print(*merge_sort(unsorted), sep=",")

0 commit comments

Comments
 (0)