Skip to content

Instantly share code, notes, and snippets.

@ryanohs
Created March 16, 2012 04:24
Show Gist options
  • Save ryanohs/2048500 to your computer and use it in GitHub Desktop.
Save ryanohs/2048500 to your computer and use it in GitHub Desktop.
Merge Sort - CoffeeScript
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