Insertion Sort




CS146

Chris Pollett

Feb 3, 2014

Outline

Introduction

Pseudo-code

Insertion Sort -- Intuition

Sorting playing cards images

Quiz

Which of the following statements is true?

  1. The statement of a computational problem involves three components one of which is an algorithm.
  2. We asserted last day that insertion sort runs in time `c n^2` for some constant `c > 0`.
  3. Algorithms are never needed for application programming.

INSERTION-SORT(A) Pseudocode

1 for j=2 to A.length
2     key = A[j]
3     // Insert A[j] into the sorted sequence A[1..j-1]
4     i = j - 1
5     while i > 0 and A[i] > key
6         A[i+1] = A[i]
7         i = i - 1
8     A[i + 1] = key

Example

Steps in sorting 5,2,4,6,1,3

Loop Invariants

Proving our INSERTION-SORT Loop Invariant

Initialization
We need to show our loop invariant holds when `j=2`. In this case the subarray `A[1.. j-1]` consists of the single element `A[1]`, which is in fact the original element `A[1]`, and it is also trivially sorted.
Maintenance
We need to show that each iteration maintains the loop invariant. Informally, the body of the for loop works by moving `A[j-1]`, `A[j-2]`, ... and so on by one position to the right until it finds the proper position for `A[j]` (lines 4-7), at which point it inserts the value of `A[j]` (line 8). The subarray `A[1..j]` then consists of the elements originally in `A[1 ..j]`, but in sorted order. Incrementing `j` for the next iteration then preserves the loop invariant.
Termination
What happens when the loop terminates? This happens when `j > Atext(.length)=n`. At that time we have `j = n +1`. Substituting `n+1` for the loop invariant, we have the subarray `A[1..n]` consists of the elements originally in `A[1..n]`, but in sorted order. I.e., the whole array is sorted. So the algorithm is correct.

Remarks on Code