Quick Sort & Top Picks
In short: quick sort's core move is partitioning: pick a pivot, rearrange the list so everything smaller sits left of it and everything else sits right, and the pivot is then in its final sorted position. Recurse on each side. It sorts in place (no second list, unlike merge sort) in O(n log n) on average — but a bad pivot choice degrades to O(n²), and the partition step alone, stopped early, finds the top-k items in about O(n) without sorting the rest.

Build Top Picks — find the top 10 without sorting 50,000
Tunebox's home screen shows the 10 most-played tracks out of 50,000. Sorting
everything to keep 10 is wasted work. The Lomuto partition uses the last
value as pivot and one wall i: everything before i is known smaller than
the pivot. Scan with j; swap each smaller value across the wall:
Lomuto partition keeps one wall, i, with everything left of it smaller than the pivot, while j scans for values to throw over the wall.
The pivot is the last value, 25, and nothing is known to be smaller yet, so the wall i starts at 0. 7 cells. pivot at index 6. i at index 0. j at index 0.
The same partition, smaller, stepped as plain code:
The mistake: thinking partitioning sorts either side. It only places the pivot — both sides still need their own recursive sort:
def partition(items, lo, hi):
pivot = items[hi]
i = lo
for j in range(lo, hi):
if items[j] < pivot:
items[i], items[j] = items[j], items[i]
i += 1
items[i], items[hi] = items[hi], items[i]
return i
nums = [9, 3, 7, 1, 5]
partition(nums, 0, len(nums) - 1)
print(nums)The same mistake shows up as a bug when partition's last line goes missing
— the recursion then trusts an index the pivot never moved to:
This should print the plays sorted low→high. It prints [42, 7, 19, 3, 88, 56] — the recursion trusts an index the pivot never moved to.
Your quick sort, partition by partition — each pivot is marked done the moment it reaches its final index.