// ---- function definitions for selection sort ---- // precondition: n >= 1, n is size of array a // postcondition: return value is index in a of largest element int findIndexOfLargest(const int a[], const int n) { int indexOfLargest = 0; for (int j = 1; j < n; j++) { if (a[j] > a[indexOfLargest]) indexOfLargest = j; } return indexOfLargest; } // precondition: none // postcondition: values of a and b have been exchanged void swap(int& a, int& b) { int temp = a; a = b; b = temp; return; } // precondition: n >= 0, and a has at least n elements // postcondition: a[0] .. a[n-1] are "sorted" -- i.e., // elements have been rearranged to be in nondecreasing order void selectionSort(int a[], const int n) { if (n > 1) { int j = findIndexOfLargest(a, n); if (j != (n-1)) swap(a[j], a[n-1]); selectionSort(a, n-1); } return; }