Choose the contract, not the name.
Compare sorting strategies using properties the application actually needs.
01 Model the idea
A sorting decision includes more than a time bound. Does the caller need the original input preserved? Must equal-key records keep their relative order? Are keys bounded integers or arbitrary comparable objects? Comparison sorting has an Ω(n log n) worst-case lower bound for general distinct keys in the comparison model, while counting and radix methods use additional key structure and a different model.
The sorted result preserves the multiset of input records and the chosen equal-key policy.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
STATE mutation, stability, key-domain and memory requirements
CHOOSE a compatible algorithm
TEST those properties before benchmarking03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
records = [("Orbit", 2), ("Atlas", 1), ("Nova", 2)]
ordered = sorted(records, key=lambda record: record[1])
print([name for name, _ in ordered])
print([name for name, _ in records])['Atlas', 'Orbit', 'Nova'] ['Orbit', 'Atlas', 'Nova']
- 1
Stable sorting preserves Orbit before Nova because their numeric keys are equal. The original record list stays unchanged.
- 2
sorted returns a new list; list.sort changes an existing list and returns None. Neither name alone describes the cost of an expensive key function.
- 3
Measure representative workloads after choosing a correct contract. Existing order, duplicates, data size, memory pressure, and key extraction can matter as much as an abstract algorithm name.
04 Count the cost
O(n log n) worst-case built-in sorting in the comparison model
O(n) for returned sorted output
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Sort records by priority and verify that equal-priority input order is preserved.
Reveal one possible solution +
records = [("first", 1), ("second", 1), ("urgent", 0)]
result = sorted(records, key=lambda item: item[1])
assert [name for name, _ in result] == ["urgent", "first", "second"]
print("Stable order verified")06 Check your reasoning
Why can counting sort beat the comparison-sorting bound?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.