MEPX
Chapter 6 of 12All chapters

Chapter 6 of 12

Quadratic and worse

Nested loops, and when they are acceptable.

O(n squared)

Comparing every item with every other item is quadratic. At a thousand items that is a million operations, which is fine. At a million items it is a trillion, which is not.

  • Bubble sort, insertion sort and naive duplicate finding are all quadratic.
  • A hash set usually turns a quadratic search into a linear one.

Beyond quadratic

O(2 to the n) and O(n factorial) appear in brute force over subsets or orderings. They are usable only for tiny n, which is why these problems get approximations.