Skip to content

Instantly share code, notes, and snippets.

@whostolebenfrog
Created June 13, 2012 21:44
Show Gist options
  • Save whostolebenfrog/2926670 to your computer and use it in GitHub Desktop.
Save whostolebenfrog/2926670 to your computer and use it in GitHub Desktop.
More clojure quicksort
;; improved version of my first solution, cut out the let by
;; using destructuring.
(defn quicksort [[pivot & others]]
(when pivot
(concat
(quicksort (filter #(>= pivot %) others))
[pivot]
(quicksort (filter #(< pivot %) others)))))
;; code golf style (shortest solution) - based on Tom C's solution
(defn q [[i & r]]
(let [f (fn [s p v] (filter #(s % p) v))]
(when i (concat (q (f <= i r)) [i] (q (f > i r))))))
;; silly multi-method (multi-dispatch) solution. Could combine 0 and 1 with a better dispatch choice
(defmulti multi-quicksort (fn [xs] (count xs)))
(defmethod multi-quicksort 0 [xs]
xs)
(defmethod multi-quicksort 1 [xs]
xs)
(defmethod multi-quicksort :default [[pivot & xs]]
(concat
(multi-quicksort (filter #(>= pivot %) xs))
[pivot]
(multi-quicksort (filter #(< pivot %) xs))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment