Practice question · Multiple choice
An O(n log n) sort applied to a nearly-sorted list can be slower than an O(n²) insertion sort on the same data. Why does the input's shape overturn the growth classes?
Hints
- How many comparisons does insertion sort make on an already-sorted list?
- Ask which case the figure O(n squared) is describing.
Show the answer
B. Because O(n²) is its worst case, and nearly-sorted data approaches O(n).
Why
Insertion sort's quadratic figure is its worst case: on sorted data each element is compared once and stays put, where merge sort does its full work regardless of input. So the comparison depends on which case the input puts you in. Quicksort is the mirror image, quadratic on sorted input with a naive pivot, and Timsort detects existing runs precisely to claim insertion sort's best case.
Practise Complexity and Performance Trade-offs
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Complexity and Performance Trade-offs
- Two algorithms are timed on one machine: the O(n) one takes 3 seconds at n = 1000 and the O(n²) one takes 1…
- Order these growth classes from the slowest-growing to the fastest-growing as n becomes large.
- A team spends a week optimising a function that accounts for 2% of runtime. What did they get, and what is…
- Big-O notation compares how algorithms scale, so an O(nlog n) algorithm always runs faster than an O(n²) one…