Clojure!
Monday, July 18, 2011 4:42:35 AM
(defn quicksort [list]
(if (< (count list) 2) list ;if the list has 0 or 1 items, return
(let [
pivot (first list) ; our pivot will be the first item
rl (rest list) ; compare against everything else
lt #(< % pivot) ; our less than predicate
gte #(>= % pivot)] ; our greater than equal predicate
(lazy-cat
(quicksort (filter lt rl)) ; recurse on filtered less
[pivot]
(quicksort (filter gte rl)) ; recurse on filtered greater than equal
))))
Make sure we give this bad boy a quick test:
(def mylist (shuffle (range 1 25))) ; make some shufled list of items (println mylist) ; take a look before sorting (time (quicksort mylist)) ; time our three runs (time (quicksort mylist)) ; the first should take the longest (time (quicksort mylist)) ; magic!
And the results, of course:
[1 2 13 20 19 21 3 22 17 14 16 7 18 10 11 5 12 4 6 8 15 24 9 23] "Elapsed time: 1.975864 msecs" "Elapsed time: 0.109321 msecs" "Elapsed time: 0.107011 msecs" (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)

