PageRenderTime 26ms CodeModel.GetById 17ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/computer_science/merge_sort.coffee

http://github.com/jashkenas/coffee-script
CoffeeScript | 18 lines | 10 code | 6 blank | 2 comment | 4 complexity | 235da5969b104924627c4b49b41c5ac7 MD5 | raw file
 1# Sorts an array in ascending natural order using merge sort.
 2merge_sort = (list) ->
 3
 4  return list if list.length is 1
 5
 6  pivot   = Math.floor list.length / 2
 7  left    = merge_sort list.slice 0, pivot
 8  right   = merge_sort list.slice pivot
 9
10  result = while left.length and right.length
11    if left[0] < right[0] then left.shift() else right.shift()
12
13  result.concat(left).concat(right)
14
15
16# Test the function.
17console.log merge_sort([3, 2, 1]).join(' ') is '1 2 3'
18console.log merge_sort([9, 2, 7, 0, 1]).join(' ') is '0 1 2 7 9'