How to sort an array of dates in C/C++?
Last Updated :
11 Sep, 2023
Given an array of dates, how to sort them.
Example:
Input:
Date arr[] = {{20, 1, 2014},
{25, 3, 2010},
{ 3, 12, 1676},
{18, 11, 1982},
{19, 4, 2015},
{ 9, 7, 2015}}
Output:
Date arr[] = {{ 3, 12, 1676},
{18, 11, 1982},
{25, 3, 2010},
{20, 1, 2014},
{19, 4, 2015},
{ 9, 7, 2015}}
We strongly recommend you to minimize your browser and try this yourself first
The idea is to use in-built function to sort function in C++. We can write our own compare function that first compares years, then months, then days.
Below is a complete C++ program.
#include<bits/stdc++.h>
using namespace std;
struct Date
{
int day, month, year;
};
bool compare( const Date &d1, const Date &d2)
{
if (d1.year < d2.year)
return true ;
if (d1.year == d2.year && d1.month < d2.month)
return true ;
if (d1.year == d2.year && d1.month == d2.month &&
d1.day < d2.day)
return true ;
return false ;
}
void sortDates(Date arr[], int n)
{
sort(arr, arr+n, compare);
}
int main()
{
Date arr[] = {{20, 1, 2014},
{25, 3, 2010},
{ 3, 12, 1676},
{18, 11, 1982},
{19, 4, 2015},
{ 9, 7, 2015}};
int n = sizeof (arr)/ sizeof (arr[0]);
sortDates(arr, n);
cout << "Sorted dates are\n" ;
for ( int i=0; i<n; i++)
{
cout << arr[i].day << " " << arr[i].month
<< " " << arr[i].year;
cout << endl;
}
}
|
Output:
Sorted dates are
3 12 1676
18 11 1982
25 3 2010
20 1 2014
19 4 2015
9 7 2015
Similarly in C, we can use qsort() function.
Related Problem:
How to efficiently sort a big list dates in 20’s
This article is contributed by Dinesh T.P.D.
Share your thoughts in the comments
Please Login to comment...