// Program sorts an integer array using the selection sort technique // Exercise 4.31 from D&D #include #include void selectionSort(int array[], int start_index, int end_index); // sorts the array via the selection sort method int findmin(int array[], int start_index, int end_index); // finds the index of the minimum element in the array void printArray(int array[], int size); // prints the array main () { const int size = 15; int numbs[size] = {6,3,8,2,0,12,13,14,1,4,5,11,10,7,8}; printArray(numbs, size); selectionSort(numbs, 0, size-1); printArray(numbs, size); return 0; } // sorts the array via the selection sort method // takes an integer array to be sorted and two indices // indicating the positions within the array to be sorted void selectionSort(int array[], int start_index, int end_index) { int temp, small_element_index; cout << "Entering selectionSort with start_index = " << start_index << endl; if (start_index < end_index) { small_element_index = findmin(array, start_index, end_index); cout << "\t Switching element at position " << small_element_index << " with element at position " << start_index << endl; // switch the smallest element into the lowest position in array temp = array[small_element_index]; array[small_element_index] = array[start_index]; array[start_index] = temp; selectionSort(array, start_index + 1, end_index); } } // finds the index of the minimum element in the array int findmin(int array[], int start_index, int end_index) { int imin = start_index, min_element = array[start_index], i; for (i = start_index + 1; i <= end_index; i++) if (array[i] < min_element) { min_element = array[i]; imin = i; } return imin; } // prints the array void printArray(int array[], int size) { int i; cout << "The array contains the following elements:" << endl; for (i = 0; i < size; i++) { cout << "[" << i << "]" << " = " << array[i] << endl; } }