//DISPLAY 17.3 Using a Generic Sorting Function //Demonstrates a generic sorting function. #include using namespace std; template void swap_values(T& variable1, T& variable2) { T temp; temp = variable1; variable1 = variable2; variable2 = temp; } template int index_of_smallest(const BaseType a[], int start_index, int number_used) { BaseType min = a[start_index]; int index_of_min = start_index; for (int index = start_index + 1; index < number_used; index++) if (a[index] < min) { min = a[index]; index_of_min = index; //min is the smallest of a[start_index] through a[index] } return index_of_min; } template void sort(BaseType a[], int number_used) { int index_of_next_smallest; for(int index = 0; index < number_used - 1; index++) {//Place the correct value in a[index]: index_of_next_smallest = index_of_smallest(a, index, number_used); swap_values(a[index], a[index_of_next_smallest]); //a[0] <= a[1] <=...<= a[index] are the smallest of the original array //elements. The rest of the elements are in the remaining positions. } } int main( ) { int i; int a[10] = {9, 8, 7, 6, 5, 1, 2, 3, 0, 4}; cout << "Unsorted integers:\n"; for (i = 0; i < 10; i++) cout << a[i] << " "; cout << endl; sort(a, 10); cout << "In sorted order the integers are:\n"; for (i = 0; i < 10; i++) cout << a[i] << " "; cout << endl; double b[5] = {5.5, 4.4, 1.1, 3.3, 2.2}; cout << "Unsorted doubles:\n"; for (i = 0; i < 5; i++) cout << b[i] << " "; cout << endl; sort(b, 5); cout << "In sorted order the doubles are:\n"; for (i = 0; i < 5; i++) cout << b[i] << " "; cout << endl; char c[7] = {'G', 'E', 'N', 'E', 'R', 'I', 'C'}; cout << "Unsorted characters:\n"; for (i = 0; i < 7; i++) cout << c[i] << " "; cout << endl; sort(c, 7); cout << "In sorted order the characters are:\n"; for (i = 0; i < 7; i++) cout << c[i] << " "; cout << endl; return 0; }