This time, Raphael has a problem with his elementary school children again. They had a pre-finals exam in class, but naturally their exams were collected in an unsorted order. Raphael graded the exams, and recorded their grades in a file called *scores.txt*. The text file consists of several lines, each line of the form <student id> <lastname> <firstname> <score(out of 100)>. His objective is to create a new file called *scores_sorted.txt*, which would contain the scores obtained by the students sorted by their **Student ID**.

Help Raphael write a program that does this. You may use an array of structures to store the data of the students, and then sort the array according to the student id's. You may use any sorting algorithm that you know (bubble sort/insertion sort/selection sort/merge sort/quicksort...). You may not use the C++ sort() method in *algorithm.h*.

```
43 Arisaka Mashiro 75
```

39 Tobisawa Misaki 94

52 Kurashina Asuka 80

```
39 Tobisawa Misaki 94
```

43 Arisaka Mashiro 75

52 Kurashina Asuka 80

This is basically an implementation problem. The only tricky part is to figure out how to compare two structures of students and when to sort them. Say we have students A and B, then we will compare the student ID's of A and B. If the ID's suggest that we need to change the order, then we swap the students A and B (the whole structs).

Here is a code that does this for you. I noticed almost everyone who submitted got this right!

#include<fstream> //Maximum number of students in the class is set to 100. const int MAX_STUDENTS = 100; // Structure to store the student records: typedef struct Student { int studentID; std::string firstName; std::string lastName; int score; } Student; // An array of Students where we will store the roster after reading the input: Student arrStudents[100]; // Actual total number of students in the class: int numStudents; // Function to read the input and populate an array of Students: void readInput() { std::ifstream fin("scores.txt",std::ios::in); int num = 0; while(!fin.eof()) { fin>>arrStudents[num].studentID>>arrStudents[num].lastName>>arrStudents[num].firstName>>arrStudents[num].score; num++; } numStudents = num; } // Function that writes arrStudents to scores_sorted.txt void writeOutput() { std::ofstream fout("scores_sorted.txt",std::ios::out); for(int i = 0; i < numStudents; i++) { fout << arrStudents[i].studentID << " " << arrStudents[i].lastName << " " << arrStudents[i].firstName << " " << arrStudents[i].score << std::endl; } } // Function that sorts arrStudents: void bubbleSort() { for(int i = 0; i < numStudents; i++) { for(int j = 0; j < numStudents - i - 1; j++) { if(arrStudents[j].studentID > arrStudents[j+1].studentID) { Student temp = arrStudents[j]; arrStudents[j] = arrStudents[j+1]; arrStudents[j+1]=temp; } } } } int main() { readInput(); bubbleSort(); writeOutput(); return 0; }