www.gutterbucket.com

Selection Sort

How it works

An outer-loop loops one less time than the length of the array. Within there is an inner-loop that starts at outer-loop's current position plus one. The inner loop then scans from this point in the array to it's end and finds the smallest item. Once the loop has finished the item at the outer-loop's current position is swapped with this smaller item.

Example Code:

  01   int lowest;
  02   int swapval;
  03   
  04   for (int x=0; x < (array.length-1); x++) {
  05      lowest = x;
  06   
  07      for (int y=x+1; y < array.length; y++)
  08         if (array[y] < array[lowest])
  09            lowest = y;
  10   
  11      swapval       = array[x];
  12      array[x]      = array[lowest];
  13      array[lowest] = swapval;
  14   }

Copyright 2000-2007  Mark R Hives  -  All rights reserved