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

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
   
typedef struct { 
    int day, month, year; 
} Date; 
   
int compare_day(const void *pd1, const void *pd2) { 
    const Date *d1 = pd1;
    const Date *d2 = pd2;
    
    if (d1->day < d2->day) 
        return 0; 
    
    return 1; 
} 
   
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_day);
       
    print(arr, size);
} 
    
    
    
/*
run:
    
1/3/1966
13/2/2007
15/12/1980
17/5/2019
18/4/2011
19/4/2011
22/5/2020
23/6/2017
   
*/

 



answered May 17, 2020 by avibootz
edited Apr 3, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
   
typedef struct { 
    char ch;
    int day, month, year; 
} Date; 
   
int compare_char(const void *pd1, const void *pd2) { 
    const Date *d1 = pd1;
    const Date *d2 = pd2;
    
    if (d1->ch < d2->ch) 
        return 0; 
    
    return 1; 
} 
   
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_char);
       
    print(arr, size);
} 
    
    
    
/*
run:
    
a 17/5/2019
b 22/5/2020
c 13/2/2007
f 23/6/2017
g 15/12/1980
n 1/3/1966
x 19/4/2011
z 18/4/2011
   
*/

 



answered May 17, 2020 by avibootz
edited Apr 3, 2024 by avibootz

Related questions

2 answers 246 views
1 answer 175 views
2 answers 232 views
1 answer 260 views
...