In C++ Description: You will use a merge sort to combine 2 lists of names into o
ID: 3824204 • Letter: I
Question
In C++
Description: You will use a merge sort to combine 2 lists of names into one master list.
The class lists are stored in two separate files, called firstClass.txt and secondClass.txt, and the results will be stored in a file called masterclass.txt.
The lists are composed of student names, in the form lastname, firstname.
The lists are in alphabetical order, by last name.
The lists are not the same length.
If 2 or more students have the same last name, they should be sorted be first name.
Names in files look like this
Last, First
Explanation / Answer
/* Assuming the file entries are- every single line is - lastname , firstname
#include <iostream.h>
#include <string>
#include <vector>
#include <fstream>
class entry{
public:
string last;
string first;
}
class Merge {
private:
vector<entry> list;
public:
void merge(vector<entry> list1, vector<entry> list2){
i = 0;
j = 0;
while (i < list1.size() && j < list2.size()){
if (list1[i].last > list2[j].last) {
list.push_back(list2[j]);
j++;
}
if (list1[i].last < list2[j].last) {
list.push_back(list1[i]);
i++;
}
if (list1[i].last == list2[j].last) {
if (list1[i].first > list2[j].last){
list.push_back(list2[j]);
j++;
}
else {
list.push_back(list1[i]);
i++;
}
}
}
if (i >= list1.size() && j < list2.size()){
while (j < list2.size()){
list.push_back(list2[j];
j++;
}
}
if (j >= list2.size() && i < lis1.size()){
while (i < list1.size()){
list.push_back(list1[i];
i++;
}
}
}
vector<entry> getlist(){
return list;
}
};
void main(){
Merge merge;
ifstream f1("firstClass.txt);
ifstream f2("secondClass.txt);
string first, last, comma;
vector<entry> list1, list2;
entry data;
int i;
merge = new Merge();
while (f1 >> last >> comma >> first){
data = new entry();
data.first = first;
data.last = last;
list1.push_back(data);
}
f1.close();
while (f2 >> last >> comma >> first){
data = new entry();
data.first = first;
data.last = last;
list2.push_back(data);
}
f2.close();
merge(list1 , list2);
ofstream f3("masterclass.txt");
for (i = 0; i<merge.getlist().size(); i++){
f3 << merge.getlist().at(i).last << " " << "," << " " << merge.getlist().at(i).first << endl;
}
f3.close();
}