I wrote a quick sort function in clojure, but it runs extremely slow. Sometimes, if the input collection grows lager, it may even overflow the stack?
Anything wrong with my code?
(defn qsort [coll]
(if (<= (count coll) 1)
coll
(let [pivot (last coll)
head-half (filter #(< % pivot) (drop-last coll))
tail-half (filter #(>= % pivot) (drop-last coll))]
(concat (qsort head-half) (vector pivot) (qsort tail-half)))))
I also read the sort function in clojure.core, but it make confused.
01 (defn sort
02 "Returns a sorted sequence of the items in coll. If no comparator is
03 supplied, uses compare. comparator must
04 implement java.util.Comparator."
05 {:added "1.0"
06 :static true}
07 ([coll]
08 (sort compare coll))
09 ([^java.util.Comparator comp coll]
10 (if (seq coll)
11 (let [a (to-array coll)]
12 (. java.util.Arrays (sort a comp))
13 (seq a))
14 ())))
The only place where recursive happens is at line 12. It just swap the two input parameters!
Could you please explain to me why this piece of code is runs?
(. java.util.Arrays (sort a comp))this call is to Arrays sort function and not a recursive call to the clojure.core sort function.Your code is slow because quick sort is a
imperative algorithmi.e it is based on concepts of imperative programming like in place array mutation. Your code is fine but the problem is it traverse the collection many times and also many intermediate collections are created.You can use array and in place array mutation to make your quick sort fast.