Skip to content

Instantly share code, notes, and snippets.

@christianblunden
Created March 20, 2012 17:51
Show Gist options
  • Save christianblunden/2138659 to your computer and use it in GitHub Desktop.
Save christianblunden/2138659 to your computer and use it in GitHub Desktop.
TCO optimised Clojure implementation of Merge Sort
(ns merge_sort.core
(:use [clojure.java.io :only (reader)])
(:gen-class :main true))
(defn merj [left right]
(loop [[lhead & ltail :as left] left
[rhead & rtail :as right] right
result []]
(cond (nil? left) (concat result right)
(nil? right) (concat result left)
true (if (<= lhead rhead)
(recur ltail right (conj result lhead))
(recur left rtail (conj result rhead))))))
(defn sawt [lst]
(let [array lst
middle (bit-shift-right (count array) 1)
[left right] (split-at middle array)]
(if (= 1 (count array))
array
(merj (sawt left) (sawt right)))))
(defn -main [& args]
(with-open [rdr (reader "IntegerArray.txt")]
(println (sawt (map #(Integer/parseInt %) (line-seq rdr))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment