Last active
April 28, 2021 10:33
-
-
Save harbirchahal/0d578d9e59cc6701dc0ab7c24e6fee7b to your computer and use it in GitHub Desktop.
Algo: Merge Sort
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
def merge_two(arr1, arr2): | |
merged = [] | |
arr1_index = 0 | |
arr2_index = 0 | |
arr1_size = len(arr1) | |
arr2_size = len(arr2) | |
while (arr1_index < arr1_size and arr2_index < arr2_size): | |
if (arr1[arr1_index] < arr2[arr2_index]): | |
merged.append(arr1[arr1_index]) | |
arr1_index += 1 | |
else: | |
merged.append(arr2[arr2_index]) | |
arr2_index += 1 | |
while (arr1_index < arr1_size): | |
merged.append(arr1[arr1_index]) | |
arr1_index += 1 | |
while (arr2_index < arr2_size): | |
merged.append(arr2[arr2_index]) | |
arr2_index += 1 | |
return merged | |
def merge_all(arrays): | |
merged = [] | |
for arr in arrays: | |
merged = merge_two(merged, arr) | |
return merged | |
# Main | |
merge_two([2, 8, 15], [5, 9, 12, 17]) # [2, 5, 8, 9, 12, 15, 17] | |
merge_all([[2, 8, 15], [5, 9, 12, 17], [3, 10, 14]]) # [2, 3, 5, 8, 9, 10, 12, 14, 15, 17] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment