Created
March 20, 2012 17:51
-
-
Save christianblunden/2138659 to your computer and use it in GitHub Desktop.
TCO optimised Clojure implementation of Merge Sort
This file contains 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
(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