Skip to content

Instantly share code, notes, and snippets.

@mrBliss
Created September 14, 2010 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrBliss/578831 to your computer and use it in GitHub Desktop.
Save mrBliss/578831 to your computer and use it in GitHub Desktop.
(defn mergesortv [coll]
(if (<= (count coll) 1)
coll
(let [middle (quot (count coll) 2)
left (mergesortv (subvec coll 0 middle))
right (mergesortv (subvec coll middle))]
(loop [left left right right l []]
(cond (empty? left) (into l right)
(empty? right) (into l left)
(< (first left) (first right))
(recur (subvec left 1) right (conj l (first left)))
:else
(recur (subvec right 1) left (conj l (first right))))))))
(defn mergesortv2 [coll]
(if (<= (count coll) 1)
coll
(let [middle (quot (count coll) 2)
left (mergesortv2 (subvec coll 0 middle))
right (mergesortv2 (subvec coll middle))]
(loop [left left right right l []]
(let [l1 (first left)
r1 (first right)]
(cond (zero? (count left)) (into l right)
(zero? (count right)) (into l left)
(<= l1 r1)
(recur (subvec left 1) right (conj l l1))
:else
(recur (subvec right 1) left (conj l r1))))))))
(defn mergesort [coll]
(if (<= (count coll) 1)
coll
(let [[left right]
(map mergesort (split-at (quot (count coll) 2) coll))]
(loop [left left right right l []]
(cond (empty? left)
(into l right)
(empty? right)
(into l left)
(< (first left) (first right))
(recur (rest left) right (conj l (first left)))
:else
(recur (rest right) left (conj l (first right))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment