liveBook · Manning

TimSort

As explained in 100 Java Mistakes and How to Avoid Them

TimSort is a stable hybrid sorting algorithm derived from merge sort and insertion sort that exploits existing ordered runs.

TimSort is a stable hybrid sorting algorithm derived from merge sort and insertion sort that exploits existing ordered runs. Since OpenJDK 7, it may detect comparator contract violations and fail with an IllegalArgumentException rather than merely producing an incorrectly ordered result. section 7.11

Overflowing comparator

A comparator such as `return account1.hashCode() - account2.hashCode();` can overflow because hash codes may have any int value. Replace subtraction with `Integer.compare(account1.hashCode(), account2.hashCode())`. With 32 randomly generated values and seed 209, sorting can throw `Comparison method violates its general contract!`; smaller collections may not expose the defect because arrays under 32 elements use a simpler path. section 7.11

Avoid TimSort failures and comparator-dependent collection corruption:

  • Test comparator behavior with large positive and negative values, and with collection sizes beyond minimal examples. section 7.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains overflow, invariant checking, size sensitivity, and collection consequences, but does not detail TimSort internals.
Examples
Demonstrates overflow with opposite-sign integers and a 32-element random array using seed 209.
What it assumes
Assumes Java comparator and collection knowledge while illustrating numeric comparison hazards explicitly.
What you can do after
Diagnose comparator failures and apply overflow-safe comparison in sorting and sorted collections.
How it connects
Connects TimSort to comparator contracts, integer overflow, sorting, TreeSet, and sorted collections.

Also explained in

Compare how 2 books explain TimSort →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.