Paste number 89442: tail-recursive qsort

Index of paste annotations: 1

Paste number 89442: tail-recursive qsort
Pasted by: chouser
When:10 months, 4 days ago
Share:Tweet this! | http://paste.lisp.org/+1X0I
Channel:#clojure
Paste contents:
Raw Source | XML | Display As
(defn qsort [xs]
  (loop [[part & parts :as work] (list xs), out []]
    (if-not work
      out
      (cond
        (coll? part) (let [[pivot & xs] part, smaller #(< % pivot)]
                      (recur (conj parts
                                    (seq (remove smaller xs))
                                    pivot
                                    (seq (filter smaller xs)))
                              out))
        (nil? part) (recur parts out)
        part (recur parts (conj out part))))))

Annotations for this paste:

Annotation number 1: lazy tail-recursive qsort
Pasted by: Chouser
When:10 months, 4 days ago
Share:Tweet this! | http://paste.lisp.org/+1X0I/1
Paste contents:
Raw Source | Display As
(defn cons-when [v coll]
  (if (empty? v) coll (cons v coll)))

(defn sort-parts [work]
  (lazy-seq
    (loop [[part & parts :as work] work]
      (when work
        (if (coll? part)
          (let [[pivot & xs] part, smaller #(< % pivot)]
            (recur (cons-when
                     (filter smaller xs)
                     (cons pivot (cons-when (remove smaller xs) parts)))))
          (cons part (sort-parts parts)))))))

(defn qsort [xs]
  (sort-parts (list xs)))

Colorize as:
Show Line Numbers
Index of paste annotations: 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.