A3: Insertion Sort

San Skulrattanakulchai

September 10, 2018

Insertion Sort

Iterative Insertion Sort

Example

Iterative Insertion Sort, continued

Correctness

Running Time Analysis

Running Time Analysis

Recursive Insertion Sort

Correctness

Running Time Analysis

Notes

  1. The items to be sorted do not have to be numbers. They can be characters, strings, etc. In general, they can come from any totally-ordered universe.
  2. We can show that the (worst-case) running time of insertion sort is Theta(n2) by proving the big-Omega estimate separately from proving the big-Oh estimate. (Use arrays that are already sorted in decreasing order.)
  3. When we can prove that the big-O estimate of an algorithm agrees with its big-Theta estimate, we say that we get a tight estimate.
  4. The exact time bound for insertion sort is Theta(n+I) where I is the number of inversions in the input. This explains why insertion sort is fast on files that are almost-sorted.

Exercise