Last active
December 12, 2015 04:28
-
-
Save romansky/4713930 to your computer and use it in GitHub Desktop.
Recursive merge sort, written in CoffeeScript
This file contains 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
nums = [8,7,9,6,5,4,3,2,1,0] | |
mergeSort = (list)-> | |
if list.length <= 1 then return list | |
left = [] | |
right = [] | |
for x in list | |
if left.length < Math.floor(list.length / 2) then left.push(x) | |
else right.push(x) | |
left = mergeSort(left) | |
right = mergeSort(right) | |
return merge(left, right) | |
merge = (left, right)-> | |
result = [] | |
ll = left.length | |
rl = right.length | |
while ll > 0 || rl > 0 | |
if ll > 0 and rl > 0 | |
if left[left.length - ll] > right[right.length - rl] | |
result.push left[left.length - ll] | |
ll -= 1 | |
else | |
result.push right[right.length - rl] | |
rl -= 1 | |
else if ll > 0 | |
result.push left[left.length - ll] | |
ll -= 1 | |
else if rl > 0 | |
result.push right[right.length - rl] | |
rl -= 1 | |
return result | |
res = mergeSort(nums) | |
console.log res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment