I need a code that sorts an array of structs in ascending order by name or age using the bubblesort algorithm.
I read all the elements and I understand the part of sorting. The problem is that I should only declare one bubblesort algorithm to be able to sort according to name or age. Also when two names or ages are the same then I should compare the elements that are not the same. For this I should use a function pointer. I have just starting using function pointers and I can't see a way out here. A little help would be much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person {
char name [30];
int age;
};
void bubblesort(struct person *prs, int n)
{
struct person temp;
int i, j , a,b;
for(i=0;i<n; i++)
{
for(j=0; j <n-1; j++)
{
a=strcmp(prs[j].name, prs[j+1].name);
b=prs[j+1].age - prs[j].age;
if(a>0)
{
temp=prs[j];
prs[j]=prs[j+1];
prs[j+1]=temp;
}
else if(a==0 && b<0)
{
temp=prs[j];
prs[j]=prs[j+1];
prs[j+1]=temp;
}
}
}
}
int main()
{
int n, i;
struct person *prs;
scanf("%d", &n);
getchar();
prs=(struct person *)malloc(sizeof(struct person)*n);
for(i=0;i<n;i++)
{
fgets(prs[i].name, 30, stdin);
prs[i].name[strlen(prs[i].name)-1]='\0';
scanf("%d", &prs[i].age);
getchar();
}
bubblesort(prs,n);
for(i=0;i<n;i++)
{
printf("{%s, %d};", prs[i].name, prs[i].age);
}
return 0;
}
qsort. It shuold provide you with enough hints about how to write your sorting function to be general.