| | | | | |

Sort By Insertion

    // C c = input container
    sorted_list<T> L;
    C::Iterator i;
    for (i = c.Begin(); i != c.End(); ++i)
      L.Insert(*i);
    // now L is a sorted list of all elements of c
    sorted_list<T>::Iterator j;
    for (i = c.Begin(), j = L.Begin(); j != L.End(); ++i, ++j)
      *i = *j;
    // now c is sorted
    
  • worst case run time = 1 + 2 + ... + n = Θ(n2)
  • replace sorted_list with faster associative container, WCRT = Θ(n log n)
  • not in place

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