How to sort an array of structures by specific element in descending order with qsort in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
  
typedef struct { 
    char ch;
    int day, month, year; 
} Date; 
  
int compare(const void *pd1, const void *pd2) { 
    const Date *d1 = pd1;
    const Date *d2 = pd2;
    if (d1->ch < d2->ch) 
        return 1; 
   
    return 0; 
} 
  
void print(Date *arr, int size) { 
    for (int i = 0; i < size; i++) { 
         printf("%c %d/%d/%d\n", arr[i].ch, arr[i].day, arr[i].month, arr[i].year); 
    } 
} 
   
int main() 
{ 
    Date arr[] = {{'c', 13,  2, 2007}, 
                  {'x', 19,  4, 2011},                   
                  {'z', 18,  4, 2011}, 
                  {'n', 1, 3, 1966}, 
                  {'a', 17,  5, 2019}, 
                  {'g', 15, 12, 1980}, 
                  {'f', 23,  6, 2017}, 
                  {'b', 22,  5, 2020}}; 
                           
    int size = sizeof(arr)/sizeof(arr[0]);
  
    qsort(arr, size, sizeof(Date), compare);
      
    print(arr, size);
} 
   
   
   
/*
run:
   
z 18/4/2011
x 19/4/2011
n 1/3/1966
g 15/12/1980
f 23/6/2017
c 13/2/2007
b 22/5/2020
a 17/5/2019
  
*/

 



answered May 17, 2020 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
   
typedef struct { 
    int day, month, year; 
} Date; 
   
int compare(const void *pd1, const void *pd2) { 
    const Date *d1 = pd1;
    const Date *d2 = pd2;
    if (d1->day < d2->day) 
        return 1; 
    
    return 0; 
} 
   
void print(Date *arr, int size) { 
    for (int i = 0; i < size; i++) { 
         printf("%d/%d/%d\n", arr[i].day, arr[i].month, arr[i].year); 
    } 
} 
    
int main() 
{ 
    Date arr[] = {{13,  2, 2007}, 
                  {19,  4, 2011},                   
                  {18,  4, 2011}, 
                  {1, 3, 1966}, 
                  {17,  5, 2019}, 
                  {15, 12, 1980}, 
                  {23,  6, 2017}, 
                  {22,  5, 2020}}; 
                            
    int size = sizeof(arr)/sizeof(arr[0]);
   
    qsort(arr, size, sizeof(Date), compare);
       
    print(arr, size);
} 
    
    
    
/*
run:
    
23/6/2017
22/5/2020
19/4/2011
18/4/2011
17/5/2019
15/12/1980
13/2/2007
1/3/1966
   
*/

 



answered May 17, 2020 by avibootz

Related questions

...