Handout - Selection sort


/*
 * FUNCTION selection_sort
 *
 * PRE:  list is an array of integers, initialized from list[0] to 
 *       list[n-1]
 * POST: the values in list[0] to list[n-1] are sorted in ascending
 *       order
 */

void selection_sort (int list [], int n)
{
  int low,     /* index of lowest position in portion of array being 
                  considered */
      small;   /* index of smallest value in portion of array being 
                  considered */

   for (low = 0; low < n; low++)
     {
       small = find_smallest_value (list, low, n-1);
       swap (list, low, small);
     }
}


/*
 * FUNCTION find_smallest_value
 *
 * PRE:  bottom <= top
 * POST: returns the index of the smallest value in array list 
 *       in the range list[bottom] to list[top]
 */

int find_smallest_value (int list [], int bottom, int top)
{
   int spos;        /* index of smallest element found so far */

   spos = bottom;

   for (int i = bottom; i <= top; i++)
       if (list[i] < list[spos])
	 spos = i;

   return (spos);
 }

/*
 * FUNCTION swap
 *
 * PRE:  p1 and p2 are valid subscripts of array list
 * POST: list[p1] <- (pre)list[p2]
         list[p2] <- (pre)list[p1]
 */

void swap (int list [], int p1, int p2)
{

   int temp = list[p1];
   list[p1] = list[p2];
   list[p2] = temp;
 }