Created
March 16, 2012 04:24
-
-
Save ryanohs/2048500 to your computer and use it in GitHub Desktop.
Merge Sort - 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
mergesort = (input) -> | |
n = input.length | |
if n == 1 | |
return input | |
pivot = Math.floor n/2 | |
a = mergesort input[0...pivot] # coffee script does not include the last element in a slice | |
b = mergesort input[pivot...n] | |
merge(a, b) | |
merge = (a, b) -> | |
i = j = k = 0 | |
c = [] | |
max = a.length + b.length | |
while i < a.length && j < b.length | |
if a[i] < b[j] | |
c[k++] = a[i++] | |
else | |
c[k++] = b[j++] | |
while i < a.length | |
c[k++] = a[i++] | |
while j < b.length | |
c[k++] = b[j++] | |
c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment