我正在尝试实现一种解决方案,用于在 clojure 中对数组进行排序所需的最小交换。
该代码有效,但求解 7 元素向量大约需要一秒钟,与 Java 中的类似解决方案相比,这非常糟糕。(已编辑)我已经尝试提供显式类型,但我尝试使用瞬态似乎没有什么不同,但是我在我的解决方案中使用了 subvec 的开放错误 - https://dev.clojure.org/jira /浏览/CLJ-787
关于如何优化解决方案的任何指示?
;; Find minimumSwaps required to sort the array. The algorithm, starts by iterating from 0 to n-1. In each iteration, it places the least element in the ith position.
(defn minimumSwaps [input]
(loop [mv input, i (long 0), swap-count (long 0)]
(if (< i (count input))
(let [min-elem (apply min (drop i mv))]
(if (not= min-elem (mv i))
(recur (swap-arr mv i min-elem),
(unchecked-inc i),
(unchecked-inc swap-count))
(recur mv,
(unchecked-inc i),
swap-count)))
swap-count)))
(defn swap-arr [vec x min-elem]
(let [y (long (.indexOf vec min-elem))]
(assoc vec x (vec y) y (vec x))))
(time (println (minimumSwaps [7 6 5 4 3 2 1])))