# Thread: Help with Sorting Structures in Database

1. You have done plenty! Thank you so much, I actually just fixed it i<cnt-2 and j<cnt-1 is the correct way to do it. Ill post the completed code.
Code:
```#include <string.h>
#include <stdio.h>
struct student
{
int student_id;
char name[30];
};
void sort(struct student st[],int cnt,int choice);
int main(void)
{
int i;
int students;
int input;
struct student stu[20];
printf("How many students in the Class?: ");
scanf("%d", &students);
for(i = 0; i < students; i++)

{
printf("Enter name: ");
scanf("%s",stu[i].name);
printf("Enter id: ");
scanf("%d", &stu[i].student_id);
printf("\n");
}

printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
scanf("%d", &input);

sort(stu,students,input);

for(i = 0; i < students; i++)
{
printf(" %s, ID: %d, has a grade: %s\n\n",
}

return 0;
}

void sort(struct student st[],int cnt,int choice)
{
int i,j;
struct student temp;

for(i=0;i<cnt-2;i++)
{
for(j=0;j<cnt-1;j++)
{
if(
(choice==0 && strcmp(st[j].name,st[j+1].name)>0)
||
(choice==1 && st[j].student_id>st[j+1].student_id)
||
)

{
temp=st[j];
st[j]=st[j+1];
st[j+1]=temp;
}

}
}
}```

2. That doesn't work. It has the same problem I mentioned in post #13. Here's what happens when I run the latest code you gave:
Code:
```\$ ./stud
How many students in the Class?: 5
Enter name: sarah
Enter id: 53214

Enter name: jack
Enter id: 54673

Enter name: daniel
Enter id: 61234

Enter name: monica
Enter id: 71234

Enter name: chris
Enter id: 64351

how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: 0
daniel, ID: 61234, has a grade: b

chris, ID: 64351, has a grade: f

jack, ID: 54673, has a grade: b

monica, ID: 71234, has a grade: c

sarah, ID: 53214, has a grade: a```
daniel should NOT come before chris. i<cnt-2 is wrong, there aren't enough iterations to bubble all the records up to their correct place, you need one more iteration, i<cnt-1.

Unfortunately, you deleted your post that described the other problem you were having (something about the last record not being sorted?). Please use i<cnt-1, then show the input you gave and output you got that was incorrect, so we can help you troubleshoot whatever problem that was.