Created
January 9, 2020 14:28
-
-
Save dtaivpp/f74a0482efbddc6332af69877f1d7716 to your computer and use it in GitHub Desktop.
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
# Courtesy of https://stackabuse.com/sorting-algorithms-in-python/ | |
def merge(left_list, right_list): | |
sorted_list = [] | |
left_list_index = right_list_index = 0 | |
# We use the list lengths often, so its handy to make variables | |
left_list_length, right_list_length = len(left_list), len(right_list) | |
for _ in range(left_list_length + right_list_length): | |
if left_list_index < left_list_length and right_list_index < right_list_length: | |
# We check which value from the start of each list is smaller | |
# If the item at the beginning of the left list is smaller, add it | |
# to the sorted list | |
if left_list[left_list_index] <= right_list[right_list_index]: | |
sorted_list.append(left_list[left_list_index]) | |
left_list_index += 1 | |
# If the item at the beginning of the right list is smaller, add it | |
# to the sorted list | |
else: | |
sorted_list.append(right_list[right_list_index]) | |
right_list_index += 1 | |
# If we've reached the end of the of the left list, add the elements | |
# from the right list | |
elif left_list_index == left_list_length: | |
sorted_list.append(right_list[right_list_index]) | |
right_list_index += 1 | |
# If we've reached the end of the of the right list, add the elements | |
# from the left list | |
elif right_list_index == right_list_length: | |
sorted_list.append(left_list[left_list_index]) | |
left_list_index += 1 | |
return sorted_list | |
def merge_sort(nums): | |
# If the list is a single element, return it | |
if len(nums) <= 1: | |
return nums | |
# Use floor division to get midpoint, indices must be integers | |
mid = len(nums) // 2 | |
# Sort and merge each half | |
left_list = merge_sort(nums[:mid]) | |
right_list = merge_sort(nums[mid:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment