| | | | | |

Classic Insertion Sort

    T A[n];   // array of size n
    T t;      // local variable
    int i, j; // loop control variables
    for (i = 1; i < n; ++i)
    {
      t = A[i];
      for (j = i; j > 0 && t < A[j - 1]; --j)
        A[j] = A[j - 1];
      A[j] = t;
    }
    
  • in place
  • stable
  • WCRT = 1 + 2 + ... + n = Θ(n2)
  • BCRT = 1 + 1 + ... + 1 = Θ(n)
  • Runtime approaches Θ(n) as input data nears being sorted
  • generic algorithm g_insertion_sort(Iter beg, Iter end)
  • requires bidirectional iterators

| | Top of Page | 8. Sorting Algorithms - 3 of 16