How to sort an array of dates in ascending order with qsort in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>

struct Date { 
    int day, month, year; 
}; 

int compare(const void *pd1, const void *pd2) { 
    const struct Date *d1 = pd1;
    const struct Date *d2 = pd2;
    if (d1->year < d2->year) 
        return 0; 
    if (d1->year == d2->year && d1->month < d2->month) 
        return 0; 
    if (d1->year == d2->year && d1->month == d2->month && d1->day < d2->day) 
        return 0; 
 
    return 1; 
} 

void print(struct 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() 
{ 
    struct Date arr[] = {{13,  2, 2007}, 
                         {19,  4, 2011},                   
                         {18,  4, 2011}, 
                         {1, 3, 1966}, 
                         {17,  5, 2019}, 
                         {17, 12, 1980}, 
                         {21,  6, 2017}, 
                         {17,  5, 2020}}; 
                         
    int size = sizeof(arr)/sizeof(arr[0]);

    qsort(arr, size, sizeof(struct Date), compare);
    
    print(arr, size);
} 
 
 
 
/*
run:
 
1/3/1966
17/12/1980
13/2/2007
18/4/2011
19/4/2011
21/6/2017
17/5/2019
17/5/2020

*/

 



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->year < d2->year) 
        return 0; 
    if (d1->year == d2->year && d1->month < d2->month) 
        return 0; 
    if (d1->year == d2->year && d1->month == d2->month && 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}, 
                  {17, 12, 1980}, 
                  {21,  6, 2017}, 
                  {17,  5, 2020}}; 
                          
    int size = sizeof(arr)/sizeof(arr[0]);
 
    qsort(arr, size, sizeof(Date), compare);
     
    print(arr, size);
} 
  
  
  
/*
run:
  
1/3/1966
17/12/1980
13/2/2007
18/4/2011
19/4/2011
21/6/2017
17/5/2019
17/5/2020
 
*/

 



answered May 17, 2020 by avibootz
edited May 17, 2020 by avibootz

Related questions

2 answers 232 views
1 answer 175 views
1 answer 148 views
1 answer 145 views
...