/*********************************************
This program reads in student/grade data from
namedgrades.txt, and prints out student names
and HW#4 scores in order from lowest to highest
score on HW#4.
**********************************************/
#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);
bool before(Student a, Student b);


/*********************************************
 ** 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];
  }

  // SORT!
  selection_sort(stu,Ns);

  // 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 #4.
bool before(Student a, Student b)
{
  return a.hw[4] < b.hw[4];
}

// THE USUAL SORTING STUFF!!
void selection_sort(Student* A, int n) 
{
  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])) {
        nexti = j;
      }
    }
    // swap A[i] and A[nexti]
    Student temp = A[i];
    A[i] = A[nexti];
    A[nexti] = temp;
  }
}