Computer Science I / Complexity and Performance Trade-offs
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
  1. How many comparisons does insertion sort make on an already-sorted list?
  2. 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.

Read the lesson: Complexity and Performance Trade-offs →

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