Question: Attached is the file sortArray.cpp. This program sorts a list of integers. The sort function sorts a partially filled array of numbers so that they
Attached is the file sortArray.cpp. This program sorts a list of integers. The sort function sorts a partially filled array of numbers so that they are ordered smallest to highest. The algorithm used is called Selection sort. The program has four functions. In this assignment, you are required to modify the sort function and the other functions to use parameterized types, aka templates, so it can sort ints, doubles, chars etc.Test the program with arrays of types int, double and chars
/* Ths program sorts a list of values (integers) from lowest to highest or from highest to lowest.
The sort function sorts a partially filled array of numbers so that they are order smallest to highest. The algorithm used is called selection sort. The algorithm rearranges the values in the array A, such that A[0] <= A[1] <= A[2] <= .....<= A[lastNum -1] */
#include
using namespace std;
const int N = 10;
// Prototypes
void fill_array(int a[], int size, int & number_used); // size is the declared size of the array N // number_used is the number of values stored in array a.
void sort(int a[], int number_used); // number_used elements of the array have values
void swap_values(int &v1, int &v2); // Interchanges the values of v1 and v2
int index_of_smallest(const int a[], int start_index, int number_used); // Returns index i such that a[i] is the smallest of the values
// Main function
int main() { cout << "Program to sort numbers from lowest to highest. ";
int a[N], number_used;
fill_array(a, N, number_used); sort (a, number_used);
cout << " In sorted order, the numbers are: ";
for (int j = 0; j < number_used; j++) cout << a[j] << " "; cout << endl; }
void fill_array(int a[], int size, int & number_used) { cout << "Enter up to " << size << " nonnegative numbers. " << "Mark end of the list with a negative integer. "; int next, index = 0; cin >> next; while ((next >= 0) && (index < size)) { a[index] = next; index++; cin >> next; } number_used = index; }
void swap_values(int &v1, int &v2) { int temp = v1; v1 = v2; v2 = temp; }
int index_of_smallest(const int a[], int start_index, int number_used) { int min = a[start_index], // Assume this is min index_of_min = start_index; for (int i = start_index + 1; i < number_used; i++) if (a[i] < min) { min = a[i]; index_of_min = i; } return index_of_min; }
void sort(int a[], int number_used) { int index_of_next_smallest; for (int i = 0; i < number_used-1; i++) { index_of_next_smallest = index_of_smallest(a, i, number_used); swap_values(a[i], a[index_of_next_smallest]); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
