Seiter's Blog

Mind of the machine

Clojure!

, , , ,

Some people were surprised to know that I love Clojure apparently. Take a look at my quick sort and compare it to my python and java variant and it will become obvious why this language rocks socks.

(defn quicksort [list]
  (if (< (count list) 2) list ;if the list has 0 or 1 items, return
    (let [
          pivot (first list) ; our pivot will be the first item
          rl (rest list) ; compare against everything else
          lt #(< % pivot) ; our less than predicate
          gte #(>= % pivot)] ; our greater than equal predicate
    (lazy-cat
      (quicksort (filter lt rl)) ; recurse on filtered less
      [pivot]
      (quicksort (filter gte rl)) ; recurse on filtered greater than equal
    ))))

Make sure we give this bad boy a quick test:

(def mylist (shuffle (range 1 25))) ; make some shufled list of items
(println mylist) ; take a look before sorting
(time (quicksort mylist)) ; time our three runs
(time (quicksort mylist)) ; the first should take the longest
(time (quicksort mylist)) ; magic!

And the results, of course:

[1 2 13 20 19 21 3 22 17 14 16 7 18 10 11 5 12 4 6 8 15 24 9 23]
"Elapsed time: 1.975864 msecs"
"Elapsed time: 0.109321 msecs"
"Elapsed time: 0.107011 msecs"
(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24)

Java Purity and Version 7Steve Jobs, 1955-2011

Write a comment

New comments have been disabled for this post.

June 2012
S M T W T F S
May 2012July 2012
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30