How to efficiently sort a big list dates in 20 's | Java program to sort an array of dates using Radix Sort ; Utilitiy function to obtain maximum date or month or year ; A function to do counting sort of arr [ ] according to given q i . e . ( 0 for day , 1 for month , 2 for year ) ; to extract last digit divide by p then % 10 Store count of occurrences in cnt [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; update p to get the next digit ; The main function that sorts array of dates using Radix Sort ; First sort by day ; Then by month ; Finally by year ; A utility function to print an array ; Driver Code ; Function Call
import java . util . * ; class GFG { static int getMax ( int arr [ ] [ ] , int n , int q ) { int maxi = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { maxi = Math . max ( maxi , arr [ i ] [ q ] ) ; } return maxi ; } static void sortDatesUtil ( int arr [ ] [ ] , int n , int q ) { int maxi = getMax ( arr , n , q ) ; int p = 1 ; while ( maxi > 0 ) { int [ ] cnt = new int [ 10 ] ; for ( int i = 0 ; i < n ; i ++ ) { cnt [ ( arr [ i ] [ q ] / p ) % 10 ] ++ ; } for ( int i = 1 ; i < 10 ; i ++ ) { cnt [ i ] += cnt [ i - 1 ] ; } int [ ] [ ] ans = new int [ n ] [ 3 ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int lastDigit = ( arr [ i ] [ q ] / p ) % 10 ; for ( int j = 0 ; j < 3 ; j ++ ) { ans [ cnt [ lastDigit ] - 1 ] [ j ] = arr [ i ] [ j ] ; } cnt [ lastDigit ] -- ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { arr [ i ] [ j ] = ans [ i ] [ j ] ; } } p *= 10 ; maxi /= 10 ; } } static void sortDates ( int dates [ ] [ ] , int n ) { sortDatesUtil ( dates , n , 0 ) ; sortDatesUtil ( dates , n , 1 ) ; sortDatesUtil ( dates , n , 2 ) ; } static void printArr ( int arr [ ] [ ] , int n ) { for ( int i = 0 ; i < 6 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { System . out . print ( arr [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int dates [ ] [ ] = { { 20 , 1 , 2014 } , { 25 , 3 , 2010 } , { 3 , 12 , 2000 } , { 18 , 11 , 2000 } , { 19 , 4 , 2015 } , { 9 , 7 , 2005 } } ; int n = dates . length ; sortDates ( dates , n ) ; System . out . print ( " Sorted Dates "); printArr ( dates , n ) ; } }