Skip to content

Instantly share code, notes, and snippets.

@damdafayton
Created July 1, 2022 11:01
Show Gist options
  • Save damdafayton/2980fd94553a5a0784610feba178cc67 to your computer and use it in GitHub Desktop.
Save damdafayton/2980fd94553a5a0784610feba178cc67 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm
def merge_sort(array1, array2)
# write your code here
sortedArray = []
while array1.length>0 && array2.length>0
p array1, array2
if (array1[0] > array2[0])
sortedArray.push(array2[0])
array2.shift()
else
sortedArray.push(array1[0])
array1.shift()
end
end
while(array1.length>0)
sortedArray.push(array1[0])
array1.shift()
end
while(array2.length>0)
sortedArray.push(array2[0])
array2.shift()
end
return sortedArray
end
p merge_sort([1, 3, 9, 11], [2, 4, 6, 8])
# => [1, 2, 3, 4, 6, 8, 9, 11]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment