Skip to content

Commit e1e5963

Browse files
Code Enhancements in merge_sort.py (TheAlgorithms#10911)
* Code Enhancements in merge_sort.py This enhanced code includes improved variable naming, error handling for user input, and more detailed docstrings. It's now more robust and readable. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 3d0a409 commit e1e5963

File tree

1 file changed

+27
-20
lines changed

1 file changed

+27
-20
lines changed

Diff for: sorts/merge_sort.py

+27-20
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,13 @@
1212

1313
def merge_sort(collection: list) -> list:
1414
"""
15-
:param collection: some mutable ordered collection with heterogeneous
16-
comparable items inside
17-
:return: the same collection ordered by ascending
15+
Sorts a list using the merge sort algorithm.
16+
17+
:param collection: A mutable ordered collection with comparable items.
18+
:return: The same collection ordered in ascending order.
19+
20+
Time Complexity: O(n log n)
21+
1822
Examples:
1923
>>> merge_sort([0, 5, 3, 2, 2])
2024
[0, 2, 2, 3, 5]
@@ -26,31 +30,34 @@ def merge_sort(collection: list) -> list:
2630

2731
def merge(left: list, right: list) -> list:
2832
"""
29-
Merge left and right.
33+
Merge two sorted lists into a single sorted list.
3034
31-
:param left: left collection
32-
:param right: right collection
33-
:return: merge result
35+
:param left: Left collection
36+
:param right: Right collection
37+
:return: Merged result
3438
"""
35-
36-
def _merge():
37-
while left and right:
38-
yield (left if left[0] <= right[0] else right).pop(0)
39-
yield from left
40-
yield from right
41-
42-
return list(_merge())
39+
result = []
40+
while left and right:
41+
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
42+
result.extend(left)
43+
result.extend(right)
44+
return result
4345

4446
if len(collection) <= 1:
4547
return collection
46-
mid = len(collection) // 2
47-
return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:]))
48+
mid_index = len(collection) // 2
49+
return merge(merge_sort(collection[:mid_index]), merge_sort(collection[mid_index:]))
4850

4951

5052
if __name__ == "__main__":
5153
import doctest
5254

5355
doctest.testmod()
54-
user_input = input("Enter numbers separated by a comma:\n").strip()
55-
unsorted = [int(item) for item in user_input.split(",")]
56-
print(*merge_sort(unsorted), sep=",")
56+
57+
try:
58+
user_input = input("Enter numbers separated by a comma:\n").strip()
59+
unsorted = [int(item) for item in user_input.split(",")]
60+
sorted_list = merge_sort(unsorted)
61+
print(*sorted_list, sep=",")
62+
except ValueError:
63+
print("Invalid input. Please enter valid integers separated by commas.")

0 commit comments

Comments
 (0)