Created
June 26, 2014 20:45
-
-
Save davidpdrsn/2c66184893fd550bd276 to your computer and use it in GitHub Desktop.
Quicksort and mergesort
This file contains hidden or 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 = (-> | |
| merge = (x, y, acc = []) -> | |
| if x.length == 0 | |
| acc.concat(y) | |
| else if y.length == 0 | |
| acc.concat(x) | |
| else if x[0] < y[0] | |
| merge x[1..-1], y, acc.concat x[0] | |
| else | |
| merge x, y[1..-1], acc.concat y[0] | |
| sort = (a) -> | |
| return a if a.length <= 1 | |
| left = a[0...a.length/2] | |
| right = a[a.length/2...a.length] | |
| merge sort(left), sort(right) | |
| )() | |
| quicksort = (-> | |
| sort = (a) -> | |
| return a if a.length <= 1 | |
| pivot = a[0] | |
| lesser = a[1..-1].filter (n) -> n < pivot | |
| greater = a[1..-1].filter (n) -> n >= pivot | |
| sort(lesser).concat [pivot], sort(greater) | |
| )() | |
| numbers = [5,2,3,1,4] | |
| console.log mergesort(numbers) # => [1,2,3,4,5] | |
| console.log quicksort(numbers) # => [1,2,3,4,5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment