Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented recursive merge sort algorithm with O(n log n) #10553

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions coding/python/merge_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env python

import random
from typing import List


def merge_sort(arr: List[int]) -> List[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)


def merge(left: List[int], right: List[int]) -> List[int]:
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged


def generate_random_list(size: int = 10, lower: int = 1, upper: int = 100) -> List[int]:
return [random.randint(lower, upper) for _ in range(size)]


def main():
"""
Executes the merge sort algorithm with a randomly generated list.
Time Complexity: O(n log n)
"""
rand_num_li = generate_random_list()
print(f"Unsorted List: {rand_num_li}")
sorted_list = merge_sort(rand_num_li)
print(f"Sorted List: {sorted_list}")


if __name__ == '__main__':
main()
Loading