// // example of recursion and sorting: // // selection sort // // main (test) program prompts for input // #include // 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); // 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); // precondition: none // postcondition: values of a and b have been exchanged void swap(int& a, int& b); // ---- main program ---- int main() { const int size = 10; int nums[size]; cout << "enter " << size << " numbers to sort:\n"; for (int i = 0; i < size; i++) cin >> nums[i]; selectionSort(nums, size); cout << "sorted numbers:\n"; for (int i = 0; i < size; i++) cout << nums[i] << endl; return 0 ; } // ---- function definitions ---- 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; } 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; } void swap(int& a, int& b) { int temp = a; a = b; b = temp; return; }