Skip to content

Instantly share code, notes, and snippets.

@tamim
Last active February 5, 2019 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tamim/c8ccaed1c40d484730bcaaf4309a4459 to your computer and use it in GitHub Desktop.
Save tamim/c8ccaed1c40d484730bcaaf4309a4459 to your computer and use it in GitHub Desktop.
/***************************************************************************
Sort a struct array in C using qsort function
****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char name[30];
int id;
int age;
};
//int ( * comparator ) ( const void *, const void * )
int comp_by_age(const void *a, const void * b)
{
struct Student *s1 = (struct Student *) a;
struct Student *s2 = (struct Student *) b;
return (int) (s1->age - s2->age); // ascending order by age
// return (int) (s1->age - s2->age); // descending order by age
}
int main()
{
struct Student a[3];
// Student 1
strcpy(a[0].name, "Mehadi");
a[0].id = 10;
a[0].age = 25 ;
// Student 2
strcpy(a[1].name, "Hasan");
a[1].id = 5;
a[1].age = 24 ;
// Student 3
strcpy(a[2].name, "Menon");
a[2].id = 100;
a[2].age = 30 ;
printf("%s\n", a[0].name);
printf("%s\n", a[1].name);
printf("%s\n", a[2].name);
//void qsort (void * base, size_t num, size_t size, int (* comparator) (const void *, const void * ));
qsort(a, 3, sizeof(struct Student), comp_by_age);
printf("\nAfter Sorting: \n");
printf("%s\n", a[0].name);
printf("%s\n", a[1].name);
printf("%s\n", a[2].name);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment