androidengineers.Book a session

Sorting Algorithms

Sorting Stability and In-Place Concepts

article20 minMedium

Stability and workspace describe different properties

A stable sort preserves input order among equal keys. An in-place sort uses limited auxiliary storage, although conventions may treat recursion-stack space separately. Neither property follows automatically from sorting correctly.

Input:  (A, score=2), (B, score=1), (C, score=2)
Stable: (B, score=1), (A, score=2), (C, score=2)

Swapping A and C in the result is still ordered by score but not stable. Stability matters when a previous ordering should survive within equal-key groups. Alternatively, specify a complete comparator with an explicit tie-breaker.

Insertion sort with strict comparisons is stable and uses constant workspace. Typical merge sort is stable with a linear buffer. Typical in-place quicksort is unstable and still uses a recursion stack.

Exercise

Sort labeled records by score and verify both monotonic keys and original relative positions of equal keys. Compare a two-pass stable sort with one comparator sorting by primary then secondary key.

Check: avoid calling an algorithm O(1)-space without stating whether stack space and returned output are included. Also verify the actual library API's documented stability rather than assuming every overload shares it.

Further reading: Sorting applications

YOUR LEARNING JOURNEY

0 of 55 available lessons completed

Progress saved in this browser. No account needed.
Sorting Stability and In-Place Concepts | Algorithms | Android Engineers