Skip to content

Instantly share code, notes, and snippets.

@flengyel
Created December 9, 2011 05:33
Show Gist options
  • Select an option

  • Save flengyel/1450328 to your computer and use it in GitHub Desktop.

Select an option

Save flengyel/1450328 to your computer and use it in GitHub Desktop.
Insetion sort in clojure
(def v (shuffle (range 10)))
(defn swap-down [v i]
(loop [j i w v]
(if (> j 0)
(let [a (nth w (dec j)) b (nth w j)]
(if (> a b)
(recur (dec j) (assoc w (dec j) b j a))
w))
w)))
(defn insertion-sort [v]
(let [n (count v)]
(loop [i 1 w v]
(if (< i n)
(recur (inc i) (swap-down w i))
w))))
(defn swap-down! [w i]
(loop [j i]
(if (> j 0)
(let [a (nth w (dec j)) b (nth w j)]
(if (> a b)
(do
(assoc! w (dec j) b j a)
(recur (dec j))))))))
(defn insertion-sort! [v]
(let [n (count v) w (transient v)]
(loop [i 1]
(if (< i n)
(do
(swap-down! w i)
(recur (inc i)))
(persistent! w)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment