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;
}
You can use an approach similar to the approach used by the standard C function qsort
.
Add a third parameter to the function bubble_sort
. For example
void bubble_sort( struct person *p,
int n,
int comp( const struct person *p1, const struct person *p2 ) );
Though it would be much better to declare the second parameter of the function as having type size_t
void bubble_sort( struct person *p,
size_t n,
int comp( const struct person *p1, const struct person *p2 ) );
Then define two functions that compare objects of the type struct person
. Each function has to return a negative value if the first item is less than the second item, positive value if the first item is greater than the second item and zero otherwise.
The functions can look like
int comp_by_name( const struct person *p1, const struct person *p2 )
{
int str_cmp = strcmp( p1->name, p2->name );
int int_cmp = ( p2->age < p1->age ) - ( p1->age < p2->age );
return str_cmp != 0 ? str_cmp : int_cmp;
}
int comp_by_age( const struct person *p1, const struct person *p2 )
{
int str_cmp = strcmp( p1->name, p2->name );
int int_cmp = ( p2->age < p1->age ) - ( p1->age < p2->age );
return int_cmp != 0 ? int_cmp : str_cmp;
}
And inside the bubble_sort
write the following if statement
if ( comp( &prs[j+1], &prs[j] ) < 0 )
{
struct person tmp = prs[j+1];
prs[j+1] = prs[j];
prs[j] = tmp;
}
And at last call the function bubble_sort
either like
bubble_sort( prs, n, comp_by_name );
if you want to sort the array by names or
bubble_sort( prs, n, comp_by_age );
if you want to sort the array by ages.