Open In App

Sort an array of string of dates in ascending order

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of strings dates[], the task is to sort these dates in ascending order. 

Note: Each date is of the form dd mmm yyyy where: 

  • Domain of dd is [0-31].
  • Domain of mmm is [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec].
  • And, yyyy is a four digit integer.

Examples: 

Input: dates[] = {“01 Mar 2015”, “11 Apr 1996”, “22 Oct 2007”} 
Output: 
11 Apr 1996 
22 Oct 2007 
01 Mar 2015

Input: dates[] = {“03 Jan 2018”, “02 Jan 2018”, “04 Jan 2017”} 
Output: 
04 Jan 2017 
02 Jan 2018 
03 Jan 2018 

Approach: Extract the days, months and years as sub-strings from the string then compare two strings by years, if years for two dates are equal then compare their months. If months are also equal than the days will decide which date appears earlier in the calendar.

Below is the implementation of the above approach:

C++




// C++ program to sort the dates in a string array
#include <bits/stdc++.h>
using namespace std;
 
// Map to store the numeric value of each month depending on
// its occurrence i.e. Jan = 1, Feb = 2 and so on.
unordered_map<string, int> monthsMap;
 
// Function which initializes the monthsMap
void sort_months()
{
    monthsMap["Jan"] = 1;
    monthsMap["Feb"] = 2;
    monthsMap["Mar"] = 3;
    monthsMap["Apr"] = 4;
    monthsMap["May"] = 5;
    monthsMap["Jun"] = 6;
    monthsMap["Jul"] = 7;
    monthsMap["Aug"] = 8;
    monthsMap["Sep"] = 9;
    monthsMap["Oct"] = 10;
    monthsMap["Nov"] = 11;
    monthsMap["Dec"] = 12;
}
 
// Comparator function to sort an array of dates
bool comp(string a, string b)
{
 
    // Comparing the years
    string str1 = a.substr(7, 5);
    string str2 = b.substr(7, 5);
    if (str1.compare(str2) != 0) {
        if (str1.compare(str2) < 0)
            return true;
        return false;
    }
 
    // Comparing the months
    string month_sub_a = a.substr(3, 3);
    string month_sub_b = b.substr(3, 3);
 
    // Taking numeric value of months from monthsMap
    int month_a = monthsMap[month_sub_a];
    int month_b = monthsMap[month_sub_b];
    if (month_a != month_b) {
        return month_a < month_b;
    }
 
    // Comparing the days
    string day_a = a.substr(0, 2);
    string day_b = b.substr(0, 2);
    if (day_a.compare(day_b) < 0)
        return true;
    return false;
}
 
// Utility function to print the contents
// of the array
void printDates(string dates[], int n)
{
    for (int i = 0; i < n; i++) {
        cout << dates[i] << endl;
    }
}
 
// Driver code
int main()
{
    string dates[] = { "24 Jul 2017", "25 Jul 2017", "11 Jun 1996",
                       "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" };
    int n = sizeof(dates) / sizeof(dates[0]);
 
    // Order the months
    sort_months();
 
    // Sort the dates
    sort(dates, dates + n, comp);
 
    // Print the sorted dates
    printDates(dates, n);
}


Java




// Java Program for the above approach
 
import java.util.*;
 
public class SortDates {
    // Map to store the numeric value of each month depending on
    // its occurrence i.e. Jan = 1, Feb = 2 and so on.
    static Map<String, Integer> monthsMap = new HashMap<>();
 
    // Function which initializes the monthsMap
    static void sortMonths() {
        monthsMap.put("Jan", 1);
        monthsMap.put("Feb", 2);
        monthsMap.put("Mar", 3);
        monthsMap.put("Apr", 4);
        monthsMap.put("May", 5);
        monthsMap.put("Jun", 6);
        monthsMap.put("Jul", 7);
        monthsMap.put("Aug", 8);
        monthsMap.put("Sep", 9);
        monthsMap.put("Oct", 10);
        monthsMap.put("Nov", 11);
        monthsMap.put("Dec", 12);
    }
 
    static int cmp(String date) {
        String[] dateParts = date.split(" ");
        int day = Integer.parseInt(dateParts[0]);
        int month = monthsMap.get(dateParts[1]);
        int year = Integer.parseInt(dateParts[2]);
 
        return year * 10000 + month * 100 + day;
    }
 
    // Utility function to print the contents
    // of the array
    static void printDates(String[] dates, int n) {
        for (int i = 0; i < n; i++) {
            System.out.println(dates[i]);
        }
    }
 
    public static void main(String[] args) {
        String[] dates = { "24 Jul 2017", "25 Jul 2017", "11 Jun 1996",
                           "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" };
        int n = dates.length;
 
        // Order the months
        sortMonths();
 
        // Sort the dates
        Arrays.sort(dates, (a, b) -> cmp(a) - cmp(b));
 
        // Print the sorted dates
        printDates(dates, n);
    }
}
 
// This code is contributed by Prince Kumar


Python3




# Python3 program to sort the dates in a string array
 
# Map to store the numeric value of each month depending on
# its occurrence i.e. Jan = 1, Feb = 2 and so on.
monthsMap=dict()
 
# Function which initializes the monthsMap
def sort_months():
 
    monthsMap["Jan"] = 1
    monthsMap["Feb"] = 2
    monthsMap["Mar"] = 3
    monthsMap["Apr"] = 4
    monthsMap["May"] = 5
    monthsMap["Jun"] = 6
    monthsMap["Jul"] = 7
    monthsMap["Aug"] = 8
    monthsMap["Sep"] = 9
    monthsMap["Oct"] = 10
    monthsMap["Nov"] = 11
    monthsMap["Dec"] = 12
 
def cmp(date):
    date=date.split()
    return int(date[2]),monthsMap[date[1]],int(date[0]),
 
 
# Utility function to print the contents
# of the array
def printDates(dates, n):
    for i in range(n):
        print(dates[i])
 
# Driver code
if __name__ == '__main__':
 
    dates = [ "24 Jul 2017", "25 Jul 2017", "11 Jun 1996",
                       "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" ]
    n = len(dates)
 
    # Order the months
    sort_months()
 
    # Sort the dates
    dates.sort(key=cmp)
 
    # Print the sorted dates
    printDates(dates, n)
 
# This code is contributed by Amartya Ghosh


C#




// C# program to sort the dates in a string array
using System;
using System.Collections.Generic;
 
class Program
{
    // Map to store the numeric value of each month depending on
    // its occurrence i.e. Jan = 1, Feb = 2 and so on.
    static Dictionary<string, int> monthsMap = new Dictionary<string, int>();
 
    // Function which initializes the monthsMap
    static void SortMonths()
    {
        monthsMap["Jan"] = 1;
        monthsMap["Feb"] = 2;
        monthsMap["Mar"] = 3;
        monthsMap["Apr"] = 4;
        monthsMap["May"] = 5;
        monthsMap["Jun"] = 6;
        monthsMap["Jul"] = 7;
        monthsMap["Aug"] = 8;
        monthsMap["Sep"] = 9;
        monthsMap["Oct"] = 10;
        monthsMap["Nov"] = 11;
        monthsMap["Dec"] = 12;
    }
 
    static int Cmp(string date)
    {
        string[] dateParts = date.Split();
        int day = int.Parse(dateParts[0]);
        int month = monthsMap[dateParts[1]];
        int year = int.Parse(dateParts[2]);
 
        return year * 10000 + month * 100 + day;
    }
 
    // Utility function to print the contents
    // of the array
    static void PrintDates(string[] dates, int n)
    {
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine(dates[i]);
        }
    }
 
    static void Main(string[] args)
    {
        string[] dates = { "24 Jul 2017", "25 Jul 2017", "11 Jun 1996",
                           "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" };
        int n = dates.Length;
 
        // Order the months
        SortMonths();
 
        // Sort the dates
        Array.Sort(dates, (a, b) => Cmp(a).CompareTo(Cmp(b)));
 
        // Print the sorted dates
        PrintDates(dates, n);
    }
}
 
// Code contributed by rishabmalhdijo


Javascript




// Map to store the numeric value of each month depending on
// its occurrence i.e. Jan = 1, Feb = 2 and so on.
let monthsMap = new Map();
 
// Function which initializes the monthsMap
function sort_months() {
    monthsMap.set("Jan", 1);
    monthsMap.set("Feb", 2);
    monthsMap.set("Mar", 3);
    monthsMap.set("Apr", 4);
    monthsMap.set("May", 5);
    monthsMap.set("Jun", 6);
    monthsMap.set("Jul", 7);
    monthsMap.set("Aug", 8);
    monthsMap.set("Sep", 9);
    monthsMap.set("Oct", 10);
    monthsMap.set("Nov", 11);
    monthsMap.set("Dec", 12);
}
 
function cmp(date) {
    date = date.split(" ");
    return [parseInt(date[2]), monthsMap.get(date[1]), parseInt(date[0])];
}
 
// Utility function to print the contents
// of the array
function printDates(dates, n) {
    for (let i = 0; i < n; i++) {
        console.log(dates[i]);
    }
}
 
// Driver code
let dates = [ "24 Jul 2017", "25 Jul 2017", "11 Jun 1996", "01 Jan 2019", "12 Aug 2005", "01 Jan 1997" ];
let n = dates.length;
 
// Order the months
sort_months();
 
// Sort the dates
dates.sort(function(a, b) {
    return cmp(a) > cmp(b) ? 1 : -1;
});
 
// Print the sorted dates
printDates(dates, n);
 
// This code has been contributed by Prince Kumar


Output

11 Jun 1996
01 Jan 1997
12 Aug 2005
24 Jul 2017
25 Jul 2017
01 Jan 2019

Complexity Analysis:

  • Time Complexity: O(N * log(N))  
  • Auxiliary Space: O(1)


Last Updated : 22 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads