CPSC 221

Sorting Complexity

Today

Announcements

  • Quiet week: no class meetings, labs or examlets
  • Homework Two is due Monday 10/19; PA2 comes out the same day
  • Examlet 4 is next week — book your seat on PrairieTest


Where we’re going

  • How fast can any sorting algorithm be?
  • Decision trees
  • A lower bound for comparison based sorting

Where are we in the sorting picture?

Best case Worst case
Insertion \(O(n)\) \(O(n^2)\)
Selection \(O(n^2)\) \(O(n^2)\)
Merge \(O(n\log n)\) \(O(n\log n)\)


https://www.toptal.com/developers/sorting-algorithms

Complexity of the sorting problem

The complexity of a problem is the runtime of the fastest algorithm that solves it.

Today: the complexity of comparison based sorting.

  • The only thing we can do with two elements is ask \(a < b\) — in constant time.
  • No peeking inside: no arithmetic, no digits.


Insertion,   Merge,   Quick,   Radix,   Selection: which are comparison based sorts?

Decision-tree encoding of a sorting algorithm

Suppose you have an unsorted array of length \(n\): \(p_1\,p_2 \ldots p_n\). We need to produce a result for every possible arrangement.

Fundamental operation: compare 2 elements using \(<\).

yes no yes no yes no yes no yes no p₁ < p₂ p₂ < p₃ p₁ < p₃ p₁ p₂ p₃ p₁ < p₃ p₂ p₃ p₁ p₂ < p₃ p₁ p₃ p₂ p₃ p₁ p₂ p₂ p₃ p₁ p₃ p₂ p₁

Lower bound on sorting (\(n\) items)

Consider a decision tree that arises from a comparison based sorting algorithm on \(n\) items:

  • Every permutation must be differentiated by the algorithm.
  • There are ______ permutations.
  • Comparisons induce a binary tree whose height determines the running time of the algorithm. (A path is a sequence of comparisons.)
  • A binary tree of height \(k\) has at most ____ leaves.

We need the shortest tree whose number of leaves is \(\ge\) the number of permutations.

What is the minimum height of a comparison tree for sorting input of size \(n\)?

Lower bound on sorting (\(n\) items)

Find the smallest \(k\) so that \(2^k \ge n!\)

Punchline

Lower bound on comparison based sorting (\(n\) items)…


Minimum height of a comparison tree for sorting input of size \(n\)…



How tall are the trees for selection and insertion sort?