Write a program where you enter a sequence of famous computer scientists’ last n
ID: 3623310 • Letter: W
Question
Write a program where you enter a sequence of famous computer scientists’ last names, see the link to a vector called Turing_winners. Terminate input by the line “No more”. Your program must be able to display Turing awards winners in alphabetical or lexicographical order using selection sort algorithm you will write in C++. The description(in pseudo code – it is not C++ code) of the sort algorithm is below:
// algorithm selectionSort( A : list of sortable items )
n = length(A)
for (k = 0; k < n-1; ++k) do:
index = k;
for (i = k+1; i < n; ++i) do:
if A[i] < A[index] then:
index = i
end if
end for
// swap two elements A[k] and A[index]
end for
// end algorithm
Explanation / Answer
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void selectionSort(string items[], int numberOfItems)
{
int startScan, minIndex;
string strName;
for(startScan = 0; startScan < (numberOfItems - 1); startScan++)
{
minIndex = startScan;
strName = items[startScan];
for(int index = startScan + 1; index < numberOfItems; index++)
{
if(items[index].c_str() < strName.c_str())
{
strName = items[index];
minIndex = index;
}
}
items[minIndex] = items[startScan];
items[startScan] = strName;
}
}
//
// Hints:
// (1) You will need two for loops.
//
// (2) Use the strcmp() function in your if-statement
// to determine when one string is less than another.
// You will need to call this function with the c_str()
// method. For example:
// strcmp(items[i].c_str(), items[j].c_str());
//
// (3) You will need a temporary string when swapping
// the two strings.
return;
}
// Print the items in the list.
void printItems(string items[], int numberOfItems)
{
for (int i=0; i < numberOfItems; i++)
{
cout << items[i] << endl;
}
cout << endl;
return;
}
int main(int argc, char **argv)
{
string starTrekCharacters[] = {
"Picard", "Riker", "Data", "La Forge", "Worf", "Dr. Crusher",
"Dr. Pulaski", "Wesley", "Troi", "Tasha", "Sisko", "Odo",
"Dax", "O'Brien", "Quark", "Dr. Bashier", "Kira", "B'Elanna",
"Chakotay", "Janeway", "Neelix", "Seven of Nine", "Tuvok",
"Doctor", "Harry", "Tom", "Kes", "Archer", "T'Pol", "Tucker",
"Reed", "Travis", "Hoshi", "Dr. Phlox", "Kirk", "Spock",
"Bones", "Scotty", "Chekov", "Uhura", "Sulu", "Nurse Chapel"
};
int numberOfCharacters = 41;
// Print the unsorted items
cout << "Items unsorted:" << endl;
printItems(starTrekCharacters, numberOfCharacters);
// Sort the items
selectionSort(starTrekCharacters, numberOfCharacters);
// Print the sorted items
cout << "Items sorted:" << endl;
printItems(starTrekCharacters, numberOfCharacters);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.