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 palace 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?
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en