sorting - How to sort a group of structures in C -
i made 4 variables structures , assigned values age
.
struct database { int id_number; int age; float salary; }; main() { struct database employee[4]; struct database current; // used later in attempted sorting employee[1].age = 12; employee[2].age = 112; employee[3].age = 2; employee[4].age = 22;
i tried various ways attempt sort these failed, example:
for(i = 0; < 4; i++) { current = employee[i];//"current" assigned same type of struct j = i; while(employee[j-1].age > current.age) { employee[j] = employee[j-1]; j = j-1; } employee[j] = current; }
many errors, pointed others in comments.
(out of bound array access, sorting algorithm not correct, etc. )
for sorting array of struct
, simplest way use qsort
need define custom comparator, following :
typedef struct database db; int sort_by_age(void *a, void *b) { db *_a = (db *)a; db *_b = (db *)b; if( _a->age > _b->age ) return -1; if( _a->age == _b->age ) return 0; return 1; }
and use like,
int no_of_employee = 4; qsort( employee, no_of_employee, sizeof(db), sort_by_age );
Comments
Post a Comment