TheAlgorithms-Python
63 строки · 1.7 Кб
1"""
2This is a pure Python implementation of the merge sort algorithm.
3
4For doctests run following command:
5python -m doctest -v merge_sort.py
6or
7python3 -m doctest -v merge_sort.py
8For manual testing run:
9python merge_sort.py
10"""
11
12
13def merge_sort(collection: list) -> list:14"""15Sorts 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
20Time Complexity: O(n log n)
21
22Examples:
23>>> merge_sort([0, 5, 3, 2, 2])
24[0, 2, 2, 3, 5]
25>>> merge_sort([])
26[]
27>>> merge_sort([-2, -5, -45])
28[-45, -5, -2]
29"""
30
31def merge(left: list, right: list) -> list:32"""33Merge two sorted lists into a single sorted list.
34
35:param left: Left collection
36:param right: Right collection
37:return: Merged result
38"""
39result = []40while left and right:41result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))42result.extend(left)43result.extend(right)44return result45
46if len(collection) <= 1:47return collection48mid_index = len(collection) // 249return merge(merge_sort(collection[:mid_index]), merge_sort(collection[mid_index:]))50
51
52if __name__ == "__main__":53import doctest54
55doctest.testmod()56
57try:58user_input = input("Enter numbers separated by a comma:\n").strip()59unsorted = [int(item) for item in user_input.split(",")]60sorted_list = merge_sort(unsorted)61print(*sorted_list, sep=",")62except ValueError:63print("Invalid input. Please enter valid integers separated by commas.")64