Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Average Case Analysis

Open in Colab

Some algorithms like quicksort use randomness to avoid deterministic pathalogical behavior. In this case, we can talk about expected runtime for an algorithm.

Quickselect

We’ll begin with a variant of quicksort that finds the kkth smallest element in an unordered list aa, or the kk-th order statistic a(k)a_{(k)}. After an initial call to partition, we can tell which array the desired entry lies in by looking at their sizes. If the left array has kk or more entries, then it contains the desired value. If it has fewer than k−1k-1 entries, then the right array contains the desired value If it has exactly k−1k-1 entries, then the desired entry is in the pivot location.

array([5, 1, 8, 6, 2, 9, 7, 3, 0, 4])
4
'd'

Analysis of Quickselect

We’ll follow the analysis found in “Algorithms from The Book” by Kenneth Lange in both this an the following section.

Let bnb_n denote the expected number of operations to find a(k)a_{(k)} on an array aa of length nn. We’ll prove that bn≤4nb_n \le 4 n. Because it takes n−1n-1 operations to create the left and right subarrays, we have

bn=n−1+1n∑j=1k−1bn−j+1n∑j=knbj−1b_n = n-1 + \frac{1}{n} \sum_{j=1}^{k-1} b_{n-j} + \frac{1}{n} \sum_{j=k}^n b_{j-1}

The terms in the first summation are the events where we must recurse into the right array, and the terms in the second summation are the events where we must recurse into the left array. The weighting by 1/n1/n reflects the fact that we have equal probability of selecting a(j)a_{(j)} as our pivot for all j=1,…,nj = 1,\dots, n.

We now argue that bn≤cnb_n \le cn, which is trivially true for n=1n=1. We proceed by induction. Suppose bk≤ckb_k\le ck for all k≤n−1k \le n-1. Recall ∑i=1m=(m+12)\sum_{i=1}^m = \binom{m+1}{2}, the above expression can be bounded

bn≤n−1+cn∑j=1k−1(n−j)+cn∑j=kn(j−1)=n−1+cn[n(k−1)−(k2)+(n2)−(k−12)]=n−1+c2n(n2+2nk−2k2−3n+4k−2)\begin{align} b_n &\le n-1 + \frac{c}{n}\sum_{j=1}^{k-1} (n-j) + \frac{c}{n} \sum_{j=k}^n (j-1)\\ &= n-1 + \frac{c}{n}\bigg[n(k-1) - \binom{k}{2} + \binom{n}{2} - \binom{k-1}{2}\bigg]\\ &= n-1 + \frac{c}{2n}(n^2 + 2nk - 2k^2 - 3n + 4k - 2) \end{align}

We want to find the value of kk which maximizes this function (a quadratic in kk), which is k=n/2+1k= n/2 + 1. Substituting this value, we have

bn≤n−1+c2n3n2/2−nb_n \le n-1 + \frac{c}{2n}{3n^2/2 - n}

Which is ≤cn\le cn where c≥4c \ge 4.

Analysis of Quicksort

Recall that in quicksort, we call the partition function in a divide-and-conquer strategy to sort the array aa.