liveBook · Manning

TimSort

As explained in Clojure: The Essential Reference

Timsort is a hybrid stable sorting algorithm that exploits existing ordered runs and combines insertion sorting with merging.

TimSort is a stable hybrid sorting algorithm used by Clojure's sort and sort-by. It exploits already ordered runs, extends short runs with insertion sort, then merges the ordered segments. section 8.3.5

Its practical characteristics are:

  • Worst-case time is O(n log n), with O(n) memory allocation. section 8.3.5
  • Performance should be reviewed for large collections; around 100,000 entries, sorting can become noticeably slower. section 8.3.5
  • Clojure sorting accepts comparators, including predicates such as >, and sort-by derives ordering through a key function. section 8.3.5

Clojure examples

(sort [:a :z :h :e :w]) ;; (:a :e :h :w :z) (sort > [18 43 3 0 9]) ;; (43 18 9 3 0) (sort-by :age [{:age 65} {:age 13} {:age 8}]) ;; ({:age 8} {:age 13} {:age 65})

How Clojure: The Essential Reference covers it

How deep it goes
Explains runs, insertion-sort extension, merging, complexity, memory, and large-input performance, but not implementation code.
Examples
Demonstrates ascending keyword sorting, descending numeric sorting, and age-based record sorting.
What it assumes
Assumes familiarity with collections and comparison functions; demonstrates sorting usage through concise Clojure expressions.
What you can do after
Apply it via Clojure's sort and sort-by with default, custom, or key-based ordering.
How it connects
Connects insertion sort and merge sort with comparators, sort, and sort-by.

Also explained in

Compare how 2 books explain TimSort →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.