Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daGrevis/8862352 to your computer and use it in GitHub Desktop.
Save daGrevis/8862352 to your computer and use it in GitHub Desktop.
Quicksort in Clojure
(defn pivot-and-rest [coll]
(let [splitted (split-at (quot (count coll) 2) coll)
second-part (second splitted)]
[(first second-part) (concat (first splitted) (rest second-part))]))
(defn quicksort [coll]
(cond
(empty? coll) []
(= (count coll) 1) coll
:else (let [[p xs] (pivot-and-rest coll)
{lesser true greater false} (group-by #(< % p) xs)]
(concat (quicksort lesser) [p] (quicksort greater)))
))
(assert (= (quicksort []) []))
(assert (= (quicksort [1]) [1]))
(assert (= (quicksort [2 1 3]) [1 2 3]))
(assert (= (quicksort [2 1 4 3]) [1 2 3 4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment