/*********************************************
This program reads in student/grade data from
namedgrades.txt, and gets a HW# x from the user
and prints out student names and HW#x scores in
order from lowest to highest score on HW#x.
**********************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*********************************************
** PROTOTYPES & STRUCT DEFINITIONS
*********************************************/
struct Student
{
int *hw;
string name;
};
void selection_sort(Student *A, int N, int x);
bool before(Student a, Student b, int x);
/*********************************************
** MAIN FUNCTION
*********************************************/
int main()
{
// Open file and read header info
int Ns, Nh;
string junk;
ifstream IN("namedgrades.txt");
IN >> Ns >> junk >> Nh >> junk;
// Create array of Ns students with Nh grades each
Student *stu = new Student[Ns];
for(int j = 0; j < Ns; j++)
stu[j].hw = new int[Nh];
// Read & store student names & grades
for(int i = 0; i < Ns; i++)
{
IN >> stu[i].name;
for(int j = 0; j < Nh; j++)
IN >> stu[i].hw[j];
}
// Get assignment number
cout << "Enter HW# to sort on: ";
int x;
cin >> x;
// SORT!
selection_sort(stu,Ns,x);
// Write out student records
for(int k = 0; k < Ns; k++)
cout << stu[k].name << " got a "
<< stu[k].hw[4] << " on HW #4" << endl;
return 0;
}
/*********************************************
** FUNCTION DEFINITIONS
*********************************************/
// Determines whether student a comes before b
// when ordered by increasing score on HW #x.
bool before(Student a, Student b, int x)
{
return a.hw[x] < b.hw[x];
}
// THE USUAL SORTING STUFF!!
void selection_sort(Student* A, int n, int x)
{
for (int i = 0; i < n - 1; ++i) {
// find nexti, the index of the next element
int nexti = i;
for (int j = i + 1; j < n; ++j) {
if (before(A[j], A[nexti], x)) {
nexti = j;
}
}
// swap A[i] and A[nexti]
Student temp = A[i];
A[i] = A[nexti];
A[nexti] = temp;
}
}