Saint Louis University |
Computer Science P125
|
Dept. of Math & Computer Science |
Our goal for this lab is to write a program which reads in a list of words and alphabetizes them. There are many different algorithms for sorting data. For this lab, we ask that you use a method known as selection sort, described as follows.
The user interface for this program should involve first asking the user how many words will be given. Then the user should enter each of the words. Then the program should sort the words and display the list of words in alphabetical orderSelect sort is based upon making repeated passes through the data as follows. During the first past, the goal is to select which word should be first in the final alphabetized result. Recall that the < operator can be used to compare two strings, with the "lesser" being that which comes first in alphabetical order.
Once this 'smallest' word has been located, that word should switch places with the word which was originally in the first entry of the array. In subsequent passes, the goal is to located the next "smallest" word out of the remaining (unsorted) words and to place it into the next spot of the array. After doing N-1 such passes, the data should be fully sorted.
To get you going, we offer the following code which reads the data from the user, but does not sort or print the data.
#include <iostream> #include <string> using namespace std; int main() { int numWords; cout << "How many words are there? "; cin >> numWords; string word[numWords]; // declare array to hold data for (int i=0; i<numWords; i++) { cin >> word[i]; // read in one such word } // now is the time to sort the list and then to print the list }
In the eventual program, printing the contents will not be done until after the words have been alphabetized. But we suggest that writing code to print out the contents of the array is a good starting point for your software development. If you are able to complete this part, you can compile and execute the program, in which case you will have a program which reads in a list of words and then echos those words back in the given order.
In starting to think about implementing selection sort, a good first step will be to see if you can write code to locate the word which should be alphabetized first in the final result. Please note that you will need to take note of the location of such word in the array; this will allow you to then relocate the word to the beginning of the array, while also relocating whatever word used to be at the beginning of the array into the vacated spot.
If you can successfully find and relocate the first word, chance are you can completely sort the list without too much additional effort. The key will be in generalizing this idea and then repeating it to place the second, and third, and fourth word, and so on.
When you are finished please submit your source code.