Skip to content

Instantly share code, notes, and snippets.

Created Oct 3, 2011
What would you like to do?
Merge sort in Clojure
; Example usage: (mergesort [5 1 8 16 25 11 4])
(ns mergesort
(:use clojure.contrib.math))
(defn merge-two
"Merge two (already sorted) vectors"
[vec1 vec2]
(let [v1f (first vec1) v2f (first vec2)]
(empty? vec1) vec2
(empty? vec2) vec1
(< v1f v2f)
(cons v1f (merge-two (rest vec1) vec2))
(cons v2f (merge-two (rest vec2) vec1)))))
(defn mergesort
"Sort a vector of numbers using the merge sort algorithm"
(let [vecsize (count vec) seam (ceil (/ vecsize 2))]
(= vecsize 1) (vector (get vec 0))
(= vecsize 2)
(if (< (get vec 0) (get vec 1))
(vector (get vec 0) (get vec 1))
(vector (get vec 1) (get vec 0))))
(mergesort (subvec vec 0 seam))
(mergesort (subvec vec seam))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment