Skip to content

Instantly share code, notes, and snippets.

@michaelficarra
Created May 1, 2012 00:50
Show Gist options
  • Save michaelficarra/2564039 to your computer and use it in GitHub Desktop.
Save michaelficarra/2564039 to your computer and use it in GitHub Desktop.
CoffeeScript quicksort
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]
@jparishy
Copy link

jparishy commented May 1, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment