<http://lib.cnfolio.com/ENG421Sorting>
Introduction to Algorithms and Programming

Selection sort



Pseudo code

START
   Get all numbers to sort
   Set the position number to zero
   WHILE the position number is one less than the quantity of numbers to sort
      Look in all positions higher than the current position to find the lowest number
      Swap the lowest number and the number at the current position
      Increase the position number by one
   END WHILE
END



Source code

  1. #include <stdio.h>
  2.  
  3. int main( void )
  4. {
  5.    int data[] = { 17, 21, 14, 19, 12 };
  6.    int numberOfItems = 5;
  7.    int outside, inside, lowest, tmpSwapValue;
  8.  
  9.    /* start at the first number and looks at every number EXCEPT the last number */
  10.    for ( outside = 0; outside < (numberOfItems - 1); outside++ )
  11.    {
  12.       /* during each round of sorting, start with the current number as the lowest number */
  13.       lowest = outside;
  14.  
  15.       /* start at the next number after the current number and compare with every number */
  16.       for (inside = (outside + 1); inside < numberOfItems; inside++ )
  17.          if ( data[inside] < data[lowest] ) lowest = inside; /* remember when a new lowest number is found */
  18.  
  19.       /* swap the position of the lowest number found with the current number */
  20.       tmpSwapValue = data[outside];
  21.       data[outside] = data[lowest];
  22.       data[lowest] = tmpSwapValue;
  23.    }
  24.  
  25.    for (outside = 0; outside < numberOfItems; outside++ ) printf( "%d ", data[outside] );
  26. }