SOURCE FILE: selectSort.cpp
typedef type-of-array-item dataType;
void SelectionSort(dataType A[], int N)
// ---------------------------------------------------
// Sorts the items in an array into ascending order.
// Precondition: A is an array of N items.
// Postcondition: The array A is sorted into ascending
// order; N is unchanged.
// Calls: IndexOfLargest, Swap.
// ---------------------------------------------------
{
// Last = index of the last item in the subarray of
// items yet to be sorted,
// L = index of the largest item found
for (int Last = N-1; Last >= 1; --Last)
{ // Invariant: A[Last+1..N-1] is sorted and >
// A[0..Last]
// select largest item in A[0..Last]
int L = IndexOfLargest(A, Last+1);
// swap largest item A[L] with A[Last]
Swap(A[L], A[Last]);
} // end for
} // end SelectionSort
int IndexOfLargest(const dataType A[], int Size)
// ---------------------------------------------------
// Finds the largest item in an array.
// Precondition: A is an array of Size items,
// Size >= 1.
// Postcondition: Returns the index of the largest
// item in the array. The arguments are unchanged.
// ---------------------------------------------------
{
int IndexSoFar = 0; // index of largest item
// found so far
for (int CurrentIndex = 1; CurrentIndex < Size;
++CurrentIndex)
{ // Invariant: A[IndexSoFar] >=
// A[0..CurrentIndex-1]
if (A[CurrentIndex] > A[IndexSoFar])
IndexSoFar = CurrentIndex;
} // end for
return IndexSoFar; // index of largest item
} // end IndexOfLargest
void Swap(dataType& X, dataType& Y)
// ---------------------------------------------------
// Swaps two items.
// Precondition: X and Y are the items to be swapped.
// Postcondition: Contents of actual locations that X
// and Y represent are swapped.
// ---------------------------------------------------
{
dataType Temp = X;
X = Y;
Y = Temp;
} // end Swap