# How to efficiently sort a big list dates in 20’s

Given a big list of dates in ’20s, how to efficiently sort the list.
Example:

```Input:
Date arr[] = {{20,  1, 2014},
{25,  3, 2010},
{ 3, 12, 2000},
{18, 11, 2001},
{19,  4, 2015},
{ 9,  7, 2005}}
Output:
Date arr[] = {{ 3, 12, 2000},
{18, 11, 2001},
{ 9,  7, 2005},
{25,  3, 2010},
{20,  1, 2014},
{19,  4, 2015}}
```

A Simple Solution is to use an O(N log N) algorithm like Merge Sort and a custom comparator. But we can sort the list in O(n) time using Radix Sort. In a typical Radix Sort implementation, we first sort by the last digit, then by second last digit, and so on. It is highly recommended to first go through the radix sort to understand this method. In this method we sort in the following order:

• First sort by day using counting sort
• Then sort by month using counting sort
• Finally, sort by year using counting sort

As the number of days, months, and years are fixed, all three steps take O(n) time. Therefore, the overall time complexity is O(n).

Below is the C++ implementation of the above idea:

## C++

 `// C++ program to sort an array` `// of dates using Radix Sort`   `#include ` `using` `namespace` `std;`   `// Utilitiy function to obtain ` `// maximum date or month or year` `int` `getMax(``int` `arr[],``int` `n, ``int` `q)` `{` `    ``int` `maxi = INT_MIN;` `    ``for``(``int` `i=0;i0){` `        ``//to extract last digit  divide ` `        ``// by p then %10` `        ``// Store count of occurrences in cnt[]` `        ``int` `cnt={0};` `        `  `        ``for``(``int` `i=0;i=0;i--)` `        ``{` `            ``int` `lastDigit = (arr[i][q]/p)%10;` `            `  `            ``// Build the output array` `            ``for``(``int` `j=0;j<3;j++)` `            ``{` `                ``ans[cnt[lastDigit]-1][j]` `                  ``=arr[i][j];    ` `            ``}` `            ``cnt[lastDigit]--;` `        ``}` `        ``// Copy the output array to arr[],` `        ``// so that arr[] now` `        ``// contains sorted numbers` `        ``// according to current digit` `        ``for``(``int` `i=0;i

Output

```Sorted Dates
18 11 2000
3 12 2000
9 7 2005
25 3 2010
20 1 2014
19 4 2015
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Improved By : nidhi_biet, tpriyanshu

Article Tags :
Practice Tags :

4

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.