#include #include #include using namespace std; class student { public: //feel free to ingore this public string fname; string lname; int id; double ex1; double ex2; double ex3; double average; }; //Read one line of info from the file, //From that info, create a student //and return it. student readOneStudentFromFile(ifstream &theFile) { student newStudent; //fill students attributes/variables with the file info theFile >> newStudent.fname; theFile >> newStudent.lname; theFile >> newStudent.ex1; theFile >> newStudent.ex2; theFile >> newStudent.ex3; return newStudent; } //Compute average score for student x, return it double computeAverage(student x) { double avg = (x.ex1 + x.ex2 + x.ex3) / 3; return avg; } void writeOneStudentToFile(student x, ofstream &outfile ) { outfile << x.fname << " " << x.lname << " " << x.average << endl; } //Write the list of students and their average //to the given output file void writeStudentsToFile(student studentList[], int n, ofstream &outfile ) { for (int i = 0; i < n; i++) { writeOneStudentToFile(studentList[i], outfile); } } //return the index of the smallest valued exam average //in given array from index s to index e //Let n be number of items in search range (e-s+1) //Run time: O( n ) int findSmallest(student list[], int s, int e) { int smallestSoFar = s; for (int i = s; i <= e; i++) { if (list[i].average < list[smallestSoFar].average) { smallestSoFar = i; } } return smallestSoFar; } //can also do student * studentList //sort array by average grade from index s to index e. //Let n be number of items in given range (e-s+1) //Run time: O( n^2 ) void selectionSort(student studentList[], int s, int e) { for (int i = s; i<=e; i++) { //find smallest item from index i to e int smallIndex = findSmallest(studentList, i, e); //swap smallest item to position i swap(studentList[i], studentList[smallIndex]); } } int main() { //step 0: opens files, etc. ifstream infile("studentData.txt"); //step 1: Get number of students from file int numStudents; infile >> numStudents; //step 2: Make an array student* studentArray = new student[numStudents]; //step 3: Read in each student's info from the file for (int i = 0; i < numStudents; i++) { //Step 3.1: Read in student's info studentArray[i] = readOneStudentFromFile(infile); } //step 4: compute average grade for each student for (int i = 0; i < numStudents; i++) { studentArray[i].average = computeAverage(studentArray[i]); } //step 5: sort students by average selectionSort(studentArray, 0, numStudents-1); //step 6: write students to output file ofstream outfile("sortedAverage.txt"); writeStudentsToFile(studentArray, numStudents, outfile); return 0; }