Modify the selectionSort function presented in this chapter so it sorts an array
ID: 3546981 • Letter: M
Question
Modify the selectionSort function presented in this chapter so it sorts an array of strings instead of an array of ints. Test the function with a driver program. Use program 9-9 as a skeleton to complete.
Program 9-9
//Include needed header files here.
int main()
{
const int SIZE = 20;
string name [SIZE] =
{"Collins, Bill", "Smith, Bart", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose,Geri",
"Tarylor, Terri", "Johnson, Jill",
"Allison, Jeff", "Looney, Joe", "Wolfe, Bill",
"James, Jean", "Weaver, Jim", "Pore, Bob",
"Rutherford, Greg", "Javens, Renee",
"Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth" };
//Insert your code to complete this program.
}
{"Collins, Bill", "Smith, Bart", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose,Geri",
"Tarylor, Terri", "Johnson, Jill",
"Allison, Jeff", "Looney, Joe", "Wolfe, Bill",
Explanation / Answer
//Include needed header files here.
#include <iostream>
#include <string>
using namespace std;
const int SIZE = 20;
void selectionSort(string arr[SIZE])
{
string temp;
//pos_min is short for position of min
int pos_min;
for (int i=0; i < SIZE-1; i++)
{
pos_min = i;//set pos_min to the current index of array
for (int j=i+1; j < SIZE; j++)
{
if (arr[j].compare(arr[pos_min]) < 0)
pos_min=j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i)
{
temp.assign(arr[i]);
arr[i].assign(arr[pos_min]);
arr[pos_min].assign(temp);
}
}
}
int main()
{
string name [SIZE] =
{"Collins, Bill", "Smith, Bart", "Allen, Jim",
"Griffin, Jim", "Stamey, Marty", "Rose,Geri",
"Tarylor, Terri", "Johnson, Jill",
"Allison, Jeff", "Looney, Joe", "Wolfe, Bill",
"James, Jean", "Weaver, Jim", "Pore, Bob",
"Rutherford, Greg", "Javens, Renee",
"Harrison, Rose", "Setzer, Cathy",
"Pike, Gordon", "Holland, Beth" };
//Insert your code to complete this program.
for(int i = 0; i < 20; i++){
cout << name[i] << endl;
}
cout << endl << endl << "After sort: " << endl;
selectionSort(name);
for(int i = 0; i < 20; i++){
cout << name[i] << endl;
}
system("pause");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.