How do I sort a 2d array based on the values of another array?

422 Views Asked by At

So i have to read some lines of text off a text file

S5555;100 70 70 100
S3333;50 50 50 50
S2222;20 50 40 70
S1111;90 80 90 85
S4444;70 80 90 50

I'm supposed to turn the texts into 2 arrays. One array stores the ID of a student and the other array stores the marks of the students (2d array).

Now I am required to sort the student ID in alphabetical order. How do i sort the 2d array based on how i sort the 1d array?

1

There are 1 best solutions below

0
On

Full disclosure: I'm a C programmer, not a C# programmer, so this may not be the standard C# approach. Regardless, it will work, it is readable, and it makes sense. This is the sort of thing I would do in c++ or java, so I bet it carries over to c#.

I'm going to take a page from my old-school C background and say that I think the concept of a struct may be helpful here.

If you are programming c#, you probably know what a class is, right? A struct is just a class that has all of its internal variables public. If I had to read a list of employees with id#'s and salaries from a file and then sort them by id number, I would have a struct like this:

public struct employee
{
    int idnum;
    int yearly_salary;
    String name;
}

each time I declare a new employee variable, it comes with 3 "fields" (idnum, yearly_salary, name). Look at this example. It creates 2 new employee strucs named emp1 and emp2.

employee emp1;
emp1.name = "Lisa Goodwin";
emp1.yearly_salary = 129200;
emp1.idnum = 3911;

employee emp2;
emp2.name = "Sevn Rushbjorn";
emp2.yearly_salary = 39800;
emp2.idnum = 8721;

If we wanted to print the salary of the employee with the lowest id#, we could do the following:

if(emp1.idnum < emp2.idnum)
{
    Console.WriteLine("salary = ${0}\n", emp1.yearly_salary);
}
else
{
    Console.WriteLine("salary = ${0}\n", emp2.yearly_salary);
}

Most importantly of all, when you swap 2 employees in an array, of course, all of their corresponding values get swapped.

employee emps[4];
//...... initialize vars from file or whatever...

swap<employee>(emps[3], emps[2]);

Using these concepts, you can compare id#'s in your sort method, (which I assume you are writing yourself because this sounds like homework), and use c#'s standard swap function to swap the 2 employees (or, in your case, students).

Simply adapt my "employee" example to students, and this should work fine.