Selection Sort
Announcements
Where we’re going
My algorithm runs in time \(\Omega(n \log n)\).
Your algorithm runs in time \(O(n!)\).
Whose is better?
We named it, evaluated its runtime, and proved it is correct.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 32 | 11 | 73 | 21 | 29 | 86 | 81 | 92 | 57 | 61 | 64 | 15 | 79 | 44 | 7 | 45 |
What does it do? How long does it take?
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 7 | 11 | 15 | 21 | 29 | 86 | 81 | 92 | 57 | 61 | 64 | 73 | 79 | 44 | 32 | 45 |
\(T(n) = \Theta(n^2)\)
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 7 | 11 | 15 | 21 | 29 | 86 | 81 | 92 | 57 | 61 | 64 | 73 | 79 | 44 | 18 | 45 |
My code crashed partway through the loop.
What is the latest iteration I could have been on?
Thm.
At the start of iteration \(i\):
C[0..i-1] is sorted.
Is that enough?
At the start of iteration \(i\): C is a permutation of what we started with, C[0..i-1] is sorted, and holds the \(i\) smallest values in C.
P(i) at the start of iteration \(i\):
A. \(C\) is a permutation of \(C_0\)
B. \(C[0] \le C[1] \le \cdots \le C[i-1]\)
C. \(\max_{0 \le k < i} C[k] \;\le\; \min_{i \le j < n} C[j]\)
\(i = 0\):
P(i) at the start of iteration \(i\):
A. \(C\) is a permutation of \(C_0\)
B. \(C[0] \le C[1] \le \cdots \le C[i-1]\)
C. \(\max_{0 \le k < i} C[k] \;\le\; \min_{i \le j < n} C[j]\)
Assume the invariant at the start of iteration \(i\). Run the body:
\(m =\) after the swap:
P(i) at the start of iteration \(i\):
A. \(C\) is a permutation of \(C_0\)
B. \(C[0] \le C[1] \le \cdots \le C[i-1]\)
C. \(\max_{0 \le k < i} C[k] \;\le\; \min_{i \le j < n} C[j]\)
Why is C[0..i] still sorted?
Why does it still hold the \(i+1\) smallest?
P(i) at the start of iteration \(i\):
A. \(C\) is a permutation of \(C_0\)
B. \(C[0] \le C[1] \le \cdots \le C[i-1]\)
C. \(\max_{0 \le k < i} C[k] \;\le\; \min_{i \le j < n} C[j]\)
Does the loop stop?
What is the state when it does?
CPSC 221