Quant Memo
Core

Stable Sorting and Tie-Breaking

Why a stable sort — one that preserves the original order of equal elements — matters for reproducible backtests and order-matching logic, and how ties get broken when the sort itself isn't naturally stable.

A sort is stable if it never changes the relative order of two elements that compare equal. Sort a list of trades by price, and two trades tied at the exact same price will come out in whichever order they went in — first in, first out — rather than being shuffled arbitrarily. Unstable sorting algorithms make no such promise: two tied elements might swap places depending on internal implementation details of the algorithm.

This matters in quant code in two very concrete places. First, in exchange order-matching: when two limit orders sit at the identical price, price-time priority says the one that arrived first gets filled first, so the matching engine's sort must be stable (or explicitly break ties by arrival timestamp) or the simulated fill order silently diverges from what a real exchange would do. Second, in backtests: if a ranking step sorts stocks by a factor score and several stocks tie exactly, an unstable sort can produce a different portfolio each run — or a different portfolio on a different machine or library version — purely from tie-breaking, making results non-reproducible even though nothing about the strategy logic changed.

Python's built-in sorted() and list.sort() are guaranteed stable (using Timsort); NumPy's default np.sort is quicksort-based and not stable unless kind='stable' is passed explicitly — a common source of silent, hard-to-debug backtest drift when code is ported between the two.

A stable sort preserves the original order of tied elements; quant code that ranks or matches on values with real ties — order-matching by price, factor rankings with exact duplicates — needs either a guaranteed-stable sort or an explicit secondary tie-break key, or results can silently vary run to run.

Related concepts

Practice in interviews

Further reading

  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, ch. 8
ShareTwitterLinkedIn