Created
March 11, 2012 05:09
-
-
Save aravinds03/2015119 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 max_first [coll] | |
"Function which returns collection with firt number beign maximum of entire collection" | |
(loop [collection (rest coll) minimum (seq [(first coll)])] | |
(if (empty? collection) minimum | |
(recur (rest collection) | |
(if (> (first collection) (first minimum)) | |
(cons (first collection) minimum) | |
;since first argument of cons is number,I need to split 'minimum' into two subsequences. | |
(cons (first minimum) (cons (first collection) (rest minimum)))))))) | |
(defn insertion_sort [coll] | |
(loop [collection coll result (seq [])] | |
(if (empty? collection) result | |
(let [temp (max_first collection)] | |
(recur (rest temp) (cons (first temp) result)))))) | |
(print (insertion_sort [2 3 1 4 -1])); |
Oops, i ended up writing some sort of selection sort :).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am not sure if this counts as insertion sort. This seems more like a variant of selection sort. There is no concept of choosing a key and inserting it in the correct position in your algorithm.
BTW you can simply replace max_first with the inbuilt max function: