| | | | | |

Selection Sort

    template < class ForwardIterator >
    void g_selection_sort (ForwardIterator beg, ForwardIterator end)
    {
      ForwardIterator i, j, k;
      for (i = beg; i != end; ++i)
      {
        k = i;
        for (j = i; j != end; ++j)
          if (*j < *k)
            k = j;
        Swap (*i, *k);
      }
    }
    
  • in place
  • not stable (call to Swap may change order of equal elements)
  • exactly n(n + 1)/2 calls to comparison operator on any input
  • run time = Θ(n2) (worst, average, best cases)
  • requires forward iterators

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