Created
October 1, 2021 12:23
-
-
Save ohaval/4c90879d1ac3e9cdec68f456e0365df0 to your computer and use it in GitHub Desktop.
The Merge sort algorithm simple and readable implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import List | |
def merge_sort(lst: List[int]) -> List[int]: | |
"""The Merge sort algorithm. | |
Wikipedia: https://en.wikipedia.org/wiki/Merge_sort | |
""" | |
if len(lst) <= 1: | |
return lst | |
middle = len(lst) // 2 | |
return order_ascend(merge_sort(lst[:middle]), merge_sort(lst[middle:])) | |
def order_ascend(left: List[int], right: List[int]) -> List[int]: | |
"""Orders the 2 lists into one ordered list for the merge sort algorithm. | |
Because of how the merge sort algorithm works, each list entered to this | |
function will already be ordered. | |
""" | |
ordered_list = [] | |
while left and right: | |
if left[0] <= right[0]: | |
ordered_list.append(left.pop(0)) | |
else: | |
ordered_list.append(right.pop(0)) | |
if not left: | |
ordered_list.extend(right) | |
else: | |
ordered_list.extend(left) | |
return ordered_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment