Skip to content

Instantly share code, notes, and snippets.

@Chouser
Created October 31, 2010 04:41
Show Gist options
  • Select an option

  • Save Chouser/656138 to your computer and use it in GitHub Desktop.

Select an option

Save Chouser/656138 to your computer and use it in GitHub Desktop.
new lazy quicksort
(defn sort-parts [work]
"Lazy, tail-recursive, incremental quicksort. Works against
and creates partitions based on the pivot, defined as 'work'."
(lazy-seq
(loop [[part & parts :as work] work] ;; #: Pull apart work
(when work
(if (coll? part) ;; #: Check partition?
(if (empty? part)
(recur parts)
(let [[pivot & xs] part ;; #: Grab pivot
smaller? #(< % pivot)] ;; #: Define checkfn
(recur (list*
(filter smaller? xs) ;; #: Work all < pivot
pivot ;; #: Work pivot itself
(remove smaller? xs) ;; #: Work all > pivot
parts)))) ;; #: concat parts
(cons part (sort-parts parts))))))) ;; #: Sort rest if not partition
(defn qsort [xs]
(sort-parts (list xs)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment