Predict the output
Quick-select style pivoting on sorted input with the first item as pivot. What does this print?
def comparisons(xs: list[int]) -> int:
if len(xs) <= 1:
return 0
pivot, rest = xs[0], xs[1:]
left = [x for x in rest if x < pivot]
right = [x for x in rest if x >= pivot]
return len(rest) + comparisons(left) + comparisons(right)
print(comparisons(list(range(20))))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 190
Right: sorted input makes every split lopsided, giving 19 + 18 + … + 1.
Choosing the first item as pivot on sorted input is the worst case, which is why real quicksorts pick pivots more carefully.
Why not the others?
- B about 86. That is roughly n log₂ n, the cost with balanced splits.
- C 20. Each level compares every remaining item against the pivot.