Skip to content

Instantly share code, notes, and snippets.

@aravinds03
Created March 11, 2012 05:09
Show Gist options
  • Save aravinds03/2015119 to your computer and use it in GitHub Desktop.
Save aravinds03/2015119 to your computer and use it in GitHub Desktop.
Insertion sort in clojure
(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]));
@Jaskirat
Copy link

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:

user> (doc max)
-------------------------
clojure.core/max
([x] [x y] [x y & more])
  Returns the greatest of the nums.
nil
user> (max 1 2 3)
3
user> (apply max (range 10))
9

@aravinds03
Copy link
Author

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