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 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 |
Take a look at http://clojure.org/sequences if you want to learn about all the cool set of library functions available to manipulate the seq abstraction. And then do try your hand at puzzles on http://4clojure.com [you can view solutions by others which is pretty awesome way to learn] and do give the koans a shot to understand some sweetness of clojure -> https://github.com/functional-koans/clojure-koans
The insert function more like a quick sort, but it's SO COOL!
But in your filter maybe should use '<='
(defn insert [l k]
"Function to do insert in sorted order"
(concat (filter #(<= % k) l) [k] (filter #(> % k) l)))
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
cool. I didn't know about "filter" method. So, I was trying to construct sequences by myself https://gist.github.com/2015119.