Last active
December 26, 2015 06:49
-
-
Save podviaznikov/7110626 to your computer and use it in GitHub Desktop.
Quicksort implemented in Clojure
This file contains 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
(defn qpart [data p] | |
(reduce (fn [acc item] | |
(cond | |
(< item p) (assoc acc :left (conj (:left acc) item)) | |
(> item p) (assoc acc :right (conj (:right acc) item)) | |
:else (assoc acc :ps (conj (:ps acc) item)))) | |
{:left [] :right [] :ps []} data)) | |
(defn quicksort [data] | |
(if (< (count data) 2) | |
data | |
(let [pindex (rand-int (count data)) | |
p (nth data pindex) | |
partitions (qpart data p) | |
left (quicksort (:left partitions)) | |
right (quicksort (:right partitions)) | |
result (concat left (:ps partitions) right)] | |
result))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment