This is my code and under it will be the question #include<iostream> #include<fs
ID: 3710947 • Letter: T
Question
This is my code and under it will be the question
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void bubbleSort(vector<string> &v) {
int n = v.size();
string temp = "";
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(v[j-1] > v[j]){
temp = v[j-1];
v[j-1] = v[j];
v[j] = temp;
}
}
}
}
int main() {
vector<string> v;
ifstream inputFile;
inputFile.open("list_in.txt");
string word;
if (inputFile.is_open()) {
while (!inputFile.eof()) {
inputFile >> word;
v.push_back(word);
}
}
bubbleSort(v);
ofstream outputFile;
outputFile.open ("list_out.txt");
for(int i=0; i<v.size(); i++){
outputFile <<v[i]<<endl;
}
outputFile.close();
inputFile.close();
return 0;
}
now under here will be the grading system my class uses
I want the output( which is my answer) to match the expected output( which is the correct answer from the system) so can you please edit my code to make it give the same answer. I am using a macbook
Explanation / Answer
Hello. You wanted to sort the names in descending order but you are doing it in ascending order. This can be achieved by a very simple correction in the bubble sort method, just change the code
v[j-1] > v[j] inside bubble sort method into
v[j-1] < v[j], and you are done. Thanks
//Corrected Code
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
void bubbleSort(vector<string> &v) {
int n = v.size();
string temp = "";
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
/*seems like you need to sort in descending order, so
*you have to check if v[j-1] is less than v[j] */
if(v[j-1] < v[j]){
temp = v[j-1];
v[j-1] = v[j];
v[j] = temp;
}
}
}
}
int main() {
vector<string> v;
ifstream inputFile;
inputFile.open("list_in.txt");
string word;
if (inputFile.is_open()) {
while (!inputFile.eof()) {
inputFile >> word;
v.push_back(word);
}
}
bubbleSort(v);
ofstream outputFile;
outputFile.open ("list_out.txt");
for(int i=0; i<v.size(); i++){
outputFile <<v[i]<<endl;
}
outputFile.close();
inputFile.close();
return 0;
}
//list_in.txt
James
Ann
Jane
Viola
William
Shawn
Vincent
Will
Nick
Matt
Zhang
Wei
//list_out.txt after running the program [output]
Zhang
William
Will
Wei
Viola
Vincent
Shawn
Nick
Matt
Jane
James
Ann
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.