Do the standard sort functions of common programming languages guarantee a stable sort?
Not all of them. Java's sorts for objects, Python's sort and sorted, and JavaScript's Array.prototype.sort (since ECMAScript 2019) are guaranteed stable. C++'s std::sort, .NET's Array.Sort and Go's sort.Sort are not, and offer separate stable variants.
| Language | Default sort | Stable? |
|---|---|---|
| Java, objects | Collections.sort |
yes, guaranteed |
| Java, primitives | Arrays.sort(int[]) |
no, and it does not matter |
| Python | sorted, list.sort |
yes, guaranteed |
| JavaScript | Array.prototype.sort |
yes, since ECMAScript 2019 |
| C++ | std::sort |
no: use std::stable_sort |
| .NET | Array.Sort |
no: use LINQ OrderBy |
| Go | sort.Sort |
no: use sort.Stable |
Whether you can rely on stability decides whether a multi-pass sort works and whether the order of equal records survives. Where the documentation does not promise it, assume it is absent, even if a test happens to keep ties in order: an unstable algorithm may keep them on small inputs and reorder them on large ones.
The Java primitives line shows when instability is harmless: two equal int values are indistinguishable, so nobody can tell whether they were swapped. That is why the library can use an unstable quick-sort for int[] but must use a stable algorithm for objects.
Go deeper:
cppreference: std::sort — "the order of equivalent elements is not guaranteed to be preserved", with
std::stable_sortnext to it.MDN: Array.prototype.sort — JavaScript's sort, stable by specification since 2019.