# Thread: Sorting within a stucture

1. ## Sorting within a stucture

Code:
```struct stud{

char name[30];
float avg;

}```
Then in the program i do this:

Code:
```struct stud students[];

..
..```
Then I need a function which will sort the grades for each student from lowest to highest..
N is the number of students
Code:
```void sort(stuct student[], int n){

int i, j, lowest, highest, temp;

for(i=0;i<n;i++)
for(j=0;j<4;j++){

if(lowest>highest){

}
}```
will this work ??
any help?

all I want to know is how to sort the 4 grades within the structure for each student.

2. Here you go... look at these: http://eternallyconfuzzled.com/tuts/sorting.html

Specifically Bubble Sort or Selection Sort as those will probably be the easiest for you to understand conceptually. You're going to want to use one of those to sort the grades, and then you're going to need another loop around your sort to go through each student.

3. Well if you make your temp to be
struct stud temp;

And swap the whole structure, then you could be onto something.

4. Except that the OP is attempting to sort an array within the struct. . . The OP appears to be sorting the grades of each student, not the students themselves.

5. Yeah, I do not want to sort the student themselves(yet), just the 4 grades within each student

6. I was also working it like this:

Code:
```for(i=0;i<n;i++) // going through each student

}```

7. Originally Posted by Salem
Well if you make your temp to be
struct stud temp;

And swap the whole structure, then you could be onto something.
Hehe... I said the same thing at first but then deleted my post. I misunderstood what he wanted to sort because I didn't bother reading the last line.

8. Originally Posted by Zeff
I was also working it like this:

Code:
```for(i=0;i<n;i++) // going through each student

}```
Is this any good ?

I'm pretty sure it will work, but I think that there is an easier way.

What do you guys think?

9. well there different ways of sorting. But that above sorting method looks ok.

ssharish2005

10. Thanks.

11. I prefer to build functions for such purposes... You trying to sort an array - so sort function need not to know that the array is a memeber of some struct or not

I think using such function makes code more readable - both inside the sort loop, and outside - where we scanning all students...
I mean smthing like
Code:
```sortGrades(int grades[], int size);

for(i=0;i<n;i++)
{