Skip to article content
Interactive Notes

Algorithms Visualized

Array Sorting

Ways to put an array in order, from quadratic to optimal

Pick a sorting algorithm and watch it rearrange the array one comparison at a time. Selection and insertion sort are simple but take quadratic time. On the other hand, merge sort, quicksort, and heapsort use divide and conquer, randomness, and a heap to reach O(nlog⁡n)O(n \log n)

Selection Sort

Each pass scans the unsorted suffix A[i..n−1]A[i..n-1] for its minimum and swaps it into position ii. The scan always runs to the end, no matter what it finds, so every input costs the same:

Best Case: Θ(n2)\Theta(n^2)

Average Case: Θ(n2)\Theta(n^2)

Worst Case: Θ(n2)\Theta(n^2)

C(n)=∑i=0n−1(n−1−i)=∑k=0n−1k=n(n−1)2=O(n2).\begin{aligned} C(n) &= \sum_{i=0}^{n-1} (n - 1 - i) \\ &= \sum_{k=0}^{n-1} k \\ &= \frac{n(n-1)}{2} \\ &= O(n^2). \end{aligned}

Insertion Sort

Each pass takes A[i]A[i] and shifts it left past every larger element in the sorted prefix A[0..i−1]A[0..i-1]. Every shift fixes exactly one inversion, a pair (i,j)(i, j) with i<ji < j and A[i]>A[j]A[i] > A[j], so the cost depends on how out of order the input is.

Best Case: Θ(n)\Theta(n)

In the best case the array is already sorted, so each element is compared once and never moves:

Cbest(n)=∑i=1n−11=n−1=Θ(n).\begin{aligned} C_{\text{best}}(n) &= \sum_{i=1}^{n-1} 1 \\ &= n - 1 \\ &= \Theta(n). \end{aligned}

Worst Case: Θ(n2)\Theta(n^2)

In the worst case the array is reversed, so element ii is shifted past all ii elements before it:

Cworst(n)=∑i=1n−1i=n(n−1)2=Θ(n2).\begin{aligned} C_{\text{worst}}(n) &= \sum_{i=1}^{n-1} i \\ &= \frac{n(n-1)}{2} \\ &= \Theta(n^2). \end{aligned}

Average Case: Θ(n2)\Theta(n^2)

On average, each of the (n2)\binom{n}{2} pairs is inverted with probability 12\frac{1}{2}, so the expected number of shifts is

E[I]=(n2)⋅12=n(n−1)4=Θ(n2).\begin{aligned} \mathbb{E}[I] &= \binom{n}{2} \cdot \frac{1}{2} \\ &= \frac{n(n-1)}{4} \\ &= \Theta(n^2). \end{aligned}