Skip to content

Commit 692a680

Browse files
authored
Implemented recursive merge sort algorithm with O(n log n) time complexity. (bregman-arie#10553)
1 parent 51f7b89 commit 692a680

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

coding/python/merge_sort.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python
2+
3+
import random
4+
from typing import List
5+
6+
7+
def merge_sort(arr: List[int]) -> List[int]:
8+
if len(arr) <= 1:
9+
return arr
10+
mid = len(arr) // 2
11+
left = merge_sort(arr[:mid])
12+
right = merge_sort(arr[mid:])
13+
return merge(left, right)
14+
15+
16+
def merge(left: List[int], right: List[int]) -> List[int]:
17+
merged = []
18+
i = j = 0
19+
while i < len(left) and j < len(right):
20+
if left[i] <= right[j]:
21+
merged.append(left[i])
22+
i += 1
23+
else:
24+
merged.append(right[j])
25+
j += 1
26+
merged.extend(left[i:])
27+
merged.extend(right[j:])
28+
return merged
29+
30+
31+
def generate_random_list(size: int = 10, lower: int = 1, upper: int = 100) -> List[int]:
32+
return [random.randint(lower, upper) for _ in range(size)]
33+
34+
35+
def main():
36+
"""
37+
Executes the merge sort algorithm with a randomly generated list.
38+
Time Complexity: O(n log n)
39+
"""
40+
rand_num_li = generate_random_list()
41+
print(f"Unsorted List: {rand_num_li}")
42+
sorted_list = merge_sort(rand_num_li)
43+
print(f"Sorted List: {sorted_list}")
44+
45+
46+
if __name__ == '__main__':
47+
main()

0 commit comments

Comments
 (0)