Created
March 10, 2012 20:54
-
-
Save Jaskirat/2013150 to your computer and use it in GitHub Desktop.
Insertion 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
| (defn insert [l k] | |
| "Function to do insert in sorted order" | |
| (concat (filter #(< % k) l) [k] (filter #(> % k) l))) | |
| (defn isort [l] | |
| "Insertion sort" | |
| (loop [r [] | |
| l l] | |
| (if (empty? l) | |
| r | |
| (recur (insert r (first l)) (rest l))))) | |
| ;;Tested in REPL | |
| ;;user> (isort (shuffle (range 10))) | |
| ;;(0 1 2 3 4 5 6 7 8 9) | |
| ;;TODO - an exercise for another day. | |
| ;;1. A lazy version | |
| ;;2. A version with actual in place inserts in to a transient collection |
What about split-with?
(defn insert [list newElement]
(let [split (split-with #(<= % newElement) list)]
(concat
(first split)
[newElement]
(second split))))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But in your filter maybe should use '<='