Question presented to candidate: "Walk me through the common sorting algorithms — bubble, selection, insertion, merge, quick and heap sort. How do they compare, and which would you pick in different situations? Feel free to show code in Python."
What a strong answer should cover:
- Compares on the right axes: best, average and worst time, extra space, stability and adaptivity.
- Correct complexities: the three simple sorts are O(n²); merge and heap sort are O(n log n) always; quicksort is O(n log n) average but O(n²) worst case.
- Explains why quicksort is still popular (in place, cache-friendly, good pivots make the worst case unlikely) and what introsort or random pivots do.
- Mentions the n log n lower bound for comparison sorts and when counting or radix sort can beat it.
- Knows that Python's
sorted/list.sortis a stable Timsort-family sort, thatsort()returnsNone, and thatkey=is preferred over a comparator. - Picks an algorithm from the input shape: nearly sorted, needs stability, tight memory, linked list, small integer keys.
Clarifying questions expected:
- How big is the input, and is it nearly sorted already?
- Do equal keys need to keep their original order (stability)?
- Is extra memory a constraint, and is the data an array or a linked list?
Code / implementation expected: Optional — a short Python implementation of one O(n²) and one O(n log n) sort is a good bonus; the comparison and the choice matter more.