Skip to content

Instantly share code, notes, and snippets.

@fitzk
Last active January 31, 2017 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitzk/643bace6a278d1039e8b02b53a5bcf75 to your computer and use it in GitHub Desktop.
Save fitzk/643bace6a278d1039e8b02b53a5bcf75 to your computer and use it in GitHub Desktop.
HackerRank: merge sort function https://repl.it/EVhs/13
# MergeSort Recursive Solution
# Python
def Merge(left, right, original):
left_len = len(left)
right_len = len(right)
left_index = 0
right_index = 0
original_index = 0
while left_index < left_len and right_index < right_len:
print('left ' + str(left))
print('right ' + str(right))
print('original ' + str(original))
print('\n')
if left[left_index] <= right[right_index]:
original[original_index] = left[left_index]
left_index = left_index + 1
else:
original[original_index] = right[right_index]
right_index = right_index + 1
original_index = original_index + 1
while left_index < left_len:
original[original_index] = left[left_index]
original_index = original_index + 1
left_index = left_index + 1
while right_index < right_len:
original[original_index] = right[right_index]
original_index = original_index + 1
right_index = right_index + 1
def MergeSort(original):
og_len = len(original)
if og_len < 2:
return
mid = int(og_len/2)
left = list(original[0:mid])
right = list(original[mid:og_len])
MergeSort(left)
MergeSort(right)
Merge(left,right,original)
original = [5,3,6,2,-9]
print('before' + str(original))
MergeSort(original)
print('after' + str(original))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment