Skip to content

Instantly share code, notes, and snippets.

@tyleralves
Created May 13, 2018 17:29
Show Gist options
  • Save tyleralves/ca4376959e3fa5c2e96694d2dbb0242c to your computer and use it in GitHub Desktop.
Save tyleralves/ca4376959e3fa5c2e96694d2dbb0242c to your computer and use it in GitHub Desktop.
MergeSort_firstTry created by tyleralves - https://repl.it/@tyleralves/MergeSortfirstTry
testUnsorted = [7,0,2,1,5,9,12,3,19]
def mergeSort(unsorted)
# Split array into two halves
# Int division (ie: 9/2 = 4)
if unsorted.length <= 1
return unsorted
end
centerIndex = unsorted.length / 2
firstHalf = unsorted[0..centerIndex-1]
secondHalf = unsorted[centerIndex..-1]
sortedFirst = mergeSort(firstHalf)
sortedSecond = mergeSort(secondHalf)
merge(sortedFirst, sortedSecond)
end
def merge(arr1, arr2)
# Add values from arr1 (i) to merged until the current value is greater than the current value in arr2 (j)
# When that occurs, do the same for arr2
merged = []
i = j = 0
while i < arr1.length && j < arr2.length
if arr1[i] < arr2[j]
merged.push(arr1[i])
i += 1
else
merged.push(arr2[j])
j += 1
end
end
# If reach the end of either array, append the remaining values of the other array to merged
if i >= arr1.length
merged.concat(arr2[j..-1])
else
merged.concat(arr1[i..-1])
end
return merged
end
mergeSort(testUnsorted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment