Home > Mobile >  sorting of array based on int value and char value in C
sorting of array based on int value and char value in C

Time:10-26

For example i have a data with an output:

Age:
Name:
Sex: 

And a sample input:

Age: 80
Name: Mary
Sex: F

Age: 100
Name: Bobby
Sex: M

Age: 45
Name: Sara
Sex: F

Age: 20
Name: Sam
Sex: M

And i wish to sort them by age in ascending order:

Age: 20
Name: Sam
Sex: M

Age: 45
Name: Sara
Sex: F

Age: 80
Name: Mary
Sex: F

Age: 100
Name: Bobby
Sex: M

How is it possible to associate/tag/append the Name and Sex array which are char arrays to Age which is an int array?

CodePudding user response:

Assuming you have a struct of Employee this qsort will do sorting for you.

  int compare( const void* a, const void* b)
     {
      struct employee *e1 = (struct employee *)a;
      struct employee *e2 = (struct employee *)b;
       int int_a = * ( (int*) e1->Age );
       int int_b = * ( (int*) e2-> Age );
       // an easy expression for comparing
       return (int_a > int_b) - (int_a < int_b);
     }
    
     qsort(values, size, sizeof(struct employee), compare ) 

CodePudding user response:

Try out looping concept. Looks pretty helpful -->
https://www.sanfoundry.com/c-program-sort-array-ascending-order/

  • Related