Part 17 / Topic 7 of 20
Sorting
Python's sorted() and list.sort() use Timsort: O(n log n) in the worst and average case, close to O(n) when the data is already mostly sorted, and stable (items that compare equal keep their original order). You almost never write your own sort in real code - but sorting is the key step inside many patterns (binary search needs sorted data; merging intervals needs them sorted by start time).
Think of sorting a stack of exam papers by roll number before handing them back - once sorted, finding any one paper is far quicker.
| Algorithm | Typical use | Time |
|---|---|---|
Timsort (sorted(), list.sort()) |
everyday sorting in Python | O(n log n), O(n) best case |
| Bubble / insertion sort | teaching only, or tiny/nearly-sorted lists | O(n²) |
Sort by more than one field with a tuple key:
orders = [("Ravi", 2, 4.5), ("Asha", 1, 9.0), ("Imran", 1, 2.0), ("Kavya", 3, 1.0)]
by_priority_then_distance = sorted(orders, key=lambda o: (o[1], o[2]))
# [('Imran', 1, 2.0), ('Asha', 1, 9.0), ('Ravi', 2, 4.5), ('Kavya', 3, 1.0)]
Sorting is usually the setup move, not the finale: binary search (one topic ahead) only works on sorted data, and the intervals topic starts every one of its solutions with exactly this sort-by-start step.
Real-world example: the delivery-orders sort above is a dispatcher's morning screen ā urgent orders first, nearest first within the same urgency. One tuple key, no custom sort code.
ā ļø Sorting mixed types without a key (plain
sorted(data)) raisesTypeErrorin Python 3 - always sort by an explicit, comparable key. Sorting is O(n log n): don't re-sort inside a loop when you could sort once outside it (the same "avoid repeated work" lesson from Part 14).
Practice: sort by a custom key or multiple criteria (priority, then distance, then name); sort objects by a computed field (age from a timestamp, distance from a point); find the k largest/smallest items after sorting (or see the heaps topic for a faster way).
Practice on LeetCode - start here: Squares of a Sorted Array Ā· Sort Colors Ā· Sort an Array
Show the full practice list (10 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Height Checker | Easy |
| Sort Array By Parity | Easy |
| Array Partition | Easy |
| Relative Sort Array | Easy |
| Custom Sort String | Medium |
| Largest Number | Medium |
| H-Index | Medium |
| Insertion Sort List | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Wiggle Sort II | Medium |
| Pancake Sorting | Medium |
Full program: examples/07_sorting.py.
Exercise 7: Sorting ā triage the support queue
Scenario: Support tickets must be worked most-urgent first; among equally urgent tickets, the one waiting longest goes first.
What to do: Write triage(tickets) where each ticket is (id, priority, minutes_waiting) and priority 1 is most urgent. Sort with one tuple key: ascending priority, then descending waiting time (negate it in the key). Print the triaged queue.
Starting data:
TICKETS = [
("T-104", 2, 31),
("T-101", 1, 5),
("T-103", 3, 60),
("T-102", 1, 12),
("T-105", 2, 8),
]
Sample output:
T-102 priority=1 waiting 12 min
T-101 priority=1 waiting 5 min
T-104 priority=2 waiting 31 min
T-105 priority=2 waiting 8 min
T-103 priority=3 waiting 60 min
Show the solution to Exercise 7
"""Exercise 7: Sorting - support tickets by priority, then age.
A tuple key sorts on the first field, breaking ties with the second.
Timsort is stable, so equal keys would keep their arrival order.
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
TICKETS = [
("T-104", 2, 31), # (id, priority 1=urgent..3=normal, minutes old)
("T-101", 1, 5),
("T-103", 3, 60),
("T-102", 1, 12),
("T-105", 2, 8),
]
def triage(tickets: list[tuple[str, int, int]]) -> list[tuple[str, int, int]]:
"""Most urgent first; within a priority, oldest (most minutes) first."""
return sorted(tickets, key=lambda t: (t[1], -t[2]))
def main() -> None:
for ticket_id, priority, age in triage(TICKETS):
print(f"{ticket_id} priority={priority} waiting {age} min")
if __name__ == "__main__":
main()