Skip to content

Instantly share code, notes, and snippets.

@Jaskirat
Created March 10, 2012 20:54
Show Gist options
  • Save Jaskirat/2013150 to your computer and use it in GitHub Desktop.
Save Jaskirat/2013150 to your computer and use it in GitHub Desktop.
Insertion sort in clojure
(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
@aravinds03
Copy link

cool. I didn't know about "filter" method. So, I was trying to construct sequences by myself https://gist.github.com/2015119.

@Jaskirat
Copy link
Author

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

@xingxing
Copy link

xingxing commented Dec 5, 2012

The insert function more like a quick sort, but it's SO COOL!

@xingxing
Copy link

xingxing commented Dec 5, 2012

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)))

@m-lautenbach
Copy link

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