Created
May 1, 2012 00:50
-
-
Save michaelficarra/2564039 to your computer and use it in GitHub Desktop.
CoffeeScript quicksort
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
qsort = (list) -> | |
return list if list.length <= 1 | |
pivotPoint = medianOfThree list | |
pivot = list[pivotPoint] | |
list.splice pivotPoint, 1, [] | |
[left, right] = partition list, (e) -> e < pivot | |
[(qsort left)..., pivot, (qsort right)...] | |
medianOfThree = (list) -> | |
return 0 if list.length < 3 | |
fst = list[0] | |
mid = list[midPos = Math.floor list.length / 2] | |
lst = list[lastPos = list.length - 1] | |
# this could instead be done efficiently in 8/3 tests on average | |
if fst < mid < lst or lst < mid < fst then midPos | |
else if mid < lst < fst or fst < lst < mid then lstPos | |
else 0 | |
partition = (list, test = (x) -> x) -> | |
pass = [] | |
fail = [] | |
for e in list | |
(if test e then pass else fail).push e | |
[pass, fail] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very cool. I had to look up the ... syntax because that was new to me. Only iterating the list once is a nice touch too, I left that out for simplicity's sake. Returning a list with named members is still something I'm coming to terms with... cool feature though.