Selection Sort

Successively find the nth smallest value and swap it with the current nth value.

Analysis

Objects Type Kind Movement Name
array to be sorted int[ ] varying received &
passed back
arr
# of elements in array int varying received n
index of smallest element int varying local smallIndex
temporary for swapping int varying local temp
index counters int, int varying local pass, j

Algorithm

  1. For pass from 0 to n-2 by 1 do (scan the sublist starting at index pass)
    1.1
    Set smallIndex to pass (current index of smallest)
    1.2
    For j from pass+1 to n-1 by 1 do
    1.2.1 If arr[j] < arr[smallIndex] then (found smaller)
    1.2.1.1 Set smallIndex to j
    1.3
    If smallIndex not equal pass (exchange elements if needed)
    1.3.1 Set temp to arr[pass]
    1.3.2 Set arr[pass] to arr[smallIndex]
    1.3.3 Set arr[smallIndex] to temp

Code

void SelectionSort (int arr[], int n)
{
   for (int pass = 0; pass < n-1; pass++)
   {
      // index of the smallest value in sublist
      int smallIndex = pass;  

      // scan the sublist starting at pass+1
      for (int j = pass+1; j < n; j++)  
         if (arr[j] < arr[smallIndex])  // found smaller
            smallIndex = j;

      // swap values, if needed
      if (smallIndex != pass)
      {
         int temp = arr[pass];
         arr[pass] = arr[smallIndex];
         arr[smallIndex] = temp;
      }  // end swap
   }  // end for
}  // end SelectionSort


Converted using latex2html on Tue Jan 31 21:56:23 CST 2006