I have an array of the ‘struct student’ in c.
struct student
{
int id;
char *name;
int age;
}
int n = 100; //number of students
struct student s[n] = ...
And I have sortByField function (Bubble sort) to sort the array in order of specific field.
void sortByField(struct student *s, int n, int fieldIndex)
{
int i, j;
for(i=n-1; i>0; i--)
{
for(j=0; j<i; j++)
{
switch (fieldIndex)
{
case 1 : if(s[j].id>s[j+1].id) swapData(&s[i], &s[j+1]); break;
case 2 : if(strcmp(s[j].name, s[j+1].name)>0) swapData(&s[i], &s[j+1]); break;
case 3 : if(s[j].age>s[j+1].age) swapData(&s[i], &s[j+1]); break;
}
}
}
}
For example, if I pass 1 to the parameter fieldIndex
sortByField(s, n, 1);
it will sort the array by id. Or, if I pass 2, it will sort by name. And so on.
Just as you saw. I used the switch-case in the loop of bubble sort to determine which field is be to compare or sort by.
But I don’t like this, I think it is redundant to must check for cases of fieldIndex again and again in the loop.
I have been trying on moving the switch-case out of the loop in order for it to be checked just once, but I am at my wit’s end.
But this switch isnt a big deal. And if it is you should consider more effective sort algorithm first…