Sorting and carrying along all the information
Sep 8, 2011 at 7:36am UTC
Hi, I'm wondering why this piece of code isn't sorting and this is the same algorithm i've used before to sort a string of arrays. It runs and compiles but after it does so it gives me a error that my program has stopped working o_O.
This is the class definition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//class declarations
class StudentInfo {
public :
string first;
string last;
int score1;
int score2;
int score3;
int total_score;
string score_status;
};
class Student {
public :
StudentInfo info;
};
And this is the sort function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
void sort(Student student[],int number)
{
string tempstr;
// sort the array
for (int pos = 0; pos < number-1; pos++)
for (int cand = pos+1; cand < number; cand++)
if (student[cand].info.first < student[pos].info.first)
{
tempstr = student[cand].info.first;
student[cand].info.first = student[pos].info.first;
student[pos].info.first = tempstr;
}
cout << endl << endl;
cout << "\t\t\tDatabase of Student SAT Scores" << endl << endl;
cout << "Students\t\t\t\tSAT Scores:" << endl;
cout << "\t\t\tScore 1\t\tScore 2\t\tScore 3" <<
"\t\tTotal Score" << "\tScore_Status" << endl << endl;
for (int index = 0; index < max_students; index++)
{
cout << student[index].info.first;
cout << " " << student[index].info.last;
cout << "\t\t" << student[index].info.score1;
cout << "\t\t" << student[index].info.score2;
cout << "\t\t" << student[index].info.score3;
cout << "\t\t" << student[index].info.total_score;
cout << "\t\t" << student[index].info.score_status;
cout << endl;
}
return ;
Last edited on Sep 8, 2011 at 7:37am UTC
Sep 8, 2011 at 10:52pm UTC
You need to swap the entire record, not parts of it.
It's not unusual for a swap to look like:
1 2 3 4 5 6
void swap(Student &a, Student &b)
{
Student tmp = a;
a = b;
b = tmp;
}
Sep 20, 2011 at 11:48pm UTC
I tried doing this instead of the swap function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void sort1(Student student[],int number)
{
Student temp;
for (int pos = 0; pos < number-1; pos++)
for (int cand = pos+1; cand < number; cand++)
if (student[cand].name < student[pos].name)
{
temp = student[cand];
student[cand] = student[pos];
student[pos] = temp;
}
return ;
}
Is this the idea of the swap function?
Sep 21, 2011 at 8:40pm UTC
Yes.
Topic archived. No new replies allowed.