Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with Selecting Sort of Structures

Status
Not open for further replies.

linuxjr

Programmer
Jun 2, 2001
135
US
I have two structures
struct StudentRec {
char name[25]; // Name of student
float average; // Student's average
};

struct Roster {
StudentRec student[100];
int numStudent;
};

I have this function that I'm trying to sort the names in order:

void sort(Roster& r)
{
for (int k =0; k < r.numStudent - 1; k++){
int next = k;
for(int j = k+1; j < r.numStudent; j++)
if(j < next)
next = j;

StudentRec temp; //Swapping buffer
strcpy(temp.name, r.student[next].name);
strcpy(r.student[next].name,r.student[k].name);
strcpy(r.student[k].name,temp.name);
}
}

I know it will fail at the if statement and I have tried next < j but that will only sort one or two. Any suggestions will be greatly appreciated. Have a nice night.
 
You must compare r.student[j].name with r.compare[k].name (by strcmp from <cstring>)! Now you always have j < next because (k+1 > k) == true. Swap all structs, not only name member (if not, what for sorting vanity?). For example:

void Sort(Roster& r)
{
StudentRec temp;
int next;

for (int k = 0; k < r.numStudent - 1; k++)
{
next = k;
for(int j = k+1; j < r.numStudent; j++)
if(strcmp(r.student[j].name,r.student[k].name) < 0)
next = j;
if (next != k) // don't swap if left min
{
//Swapping buffer
temp = r.student[next];
r.student[next] = r.student[k];
r.student[k] = temp;
}
}
}
 
Since this is C++ code, you could try making use of the STL.

Something like..

Code:
struct StudentRec
{
 bool operator < (StudentRec &rhs)
 {
  return name < rhs.name;
 }
 string name;
 float average;
};

struct Roster
{
 vector<StudentRec> student;
};

int main()
{
 //set up test data
 StudentRec s1;
 StudentRec s2;
 StudentRec s3;
 s1.name = &quot;Smith&quot;;
 s2.name = &quot;Jones&quot;;
 s3.name = &quot;Lopez&quot;;

 Roster r;
 r.student.push_back(s1);
 r.student.push_back(s2);
 r.student.push_back(s3);
 //end test data set up

 //sort Roster
 sort(r.student.begin(), r.student.end());

 return 0;
};
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top