This is a clojure program to read integers from a file and count the number of inversions i.e the number of times a larger number appears before a smaller number in a sequence. It implements a O(n^2) algorithm, and takes about 30 minutes to run on an input of size 100,000.
(defn count-inversions
[file]
(let [int-list (vec (map #(Integer/parseInt %)
(clojure.string/split (slurp file) #"\r\n")))]
(loop [c 0
t-list int-list]
(let [size (count t-list)]
(if (empty? t-list)
c
(recur (reduce #(if (< %2 (first t-list)) (inc %1) %1) c (subvec t-list 1 (dec size)))
(subvec t-list 1 (dec size))))))))
This algorithm when implemented in Java takes only a few seconds to complete. Why such a large difference?
timeon various parts to see where the time is being spent. Using along-arrayand indexes might speed things up, but I can't see it being 4 orders of magnitude different.