Created
December 9, 2011 05:33
-
-
Save flengyel/1450328 to your computer and use it in GitHub Desktop.
Insetion sort in clojure
This file contains hidden or 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
| (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