Insertion Sort
Announcements
Where we’re going
Thm. After selectionSort(C) returns, C is a permutation of \(C_0\) and \(C[0] \le C[1] \le \cdots \le C[n-1]\).
Loop invariant. \(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]\)
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]\)
Check that the loop invariant holds at the start of the loop:
(\(i =\) ___)
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:
Line 3:
Line 4:
Check the invariants:
A.
B.
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]\)
Does the loop stop?
What is the state when it does?
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| 8 | 14 | 26 | 32 | 19 | 35 | 2 | 10 |
What does it do? How long does it take? Is it correct?
slide correct?Thm. If C[0..loc-1] is sorted, then afterwards C is a permutation of \(C_0\) and C[0..loc] is sorted.
C is a _______ of \(C_0\)C[0..___] is sorted, and C[___..loc] is sortedslide, continuedQ(j) at the top of the test:
A. \(C\) is a permutation of \(C_0\)
B. \(C[0..j-1]\) and \(C[j..\mathit{loc}]\) are each sorted
C. \(\max_{0 \le k < j} C[k] \;\le\; \min_{j < k \le \mathit{loc}} C[k]\)
Initialization: \(j =\) ___
Restoration:
slide, terminationQ(j) at the top of the test:
A. \(C\) is a permutation of \(C_0\)
B. \(C[0..j-1]\) and \(C[j..\mathit{loc}]\) are each sorted
C. \(\max_{0 \le k < j} C[k] \;\le\; \min_{j < k \le \mathit{loc}} C[k]\)
The loop exits when __________ or __________
Case 1:
Case 2:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| 32 | 14 | 26 | 8 | 19 | 35 | 2 | 10 |
Worst case running time:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
Best case?
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
Correctness proof —
C is a _______ of the input, and C[0..___] is sortedC[0..___] sorted?CPSC 221