How to efficiently sort a big list dates in 20's - GeeksforGeeks
A Simple Solution is to use a O(nLogn) algorithm like Merge Sort. We can sort the list in O(n) time using Radix Sort. In a typical Radix Sort implementation, we first sort by last digit, then by second last digit, and so on. Here we sort in following order.
1) First sort by day using counting sort
2) Then sort by month using counting sort
3) Finally sort by year using counting sort
Read full article from How to efficiently sort a big list dates in 20's - GeeksforGeeks
A Simple Solution is to use a O(nLogn) algorithm like Merge Sort. We can sort the list in O(n) time using Radix Sort. In a typical Radix Sort implementation, we first sort by last digit, then by second last digit, and so on. Here we sort in following order.
1) First sort by day using counting sort
2) Then sort by month using counting sort
3) Finally sort by year using counting sort
void radixSortDates(Date arr[], int n){ // First sort by day countSortDay(arr, n); // Then by month countSortMonth(arr, n); // Finally by year countSortYear(arr, n);}// A function to do counting sort of arr[] according to// dayvoid countSortDay(Date arr[], int n){ Date output[n]; // output array int i, count[31] = {0}; // Store count of occurrences in count[] for (i=0; i<n; i++) count[arr[i].d - 1]++; // Change count[i] so that count[i] now contains // actual position of this day in output[] for (i=1; i<31; i++) count[i] += count[i-1]; // Build the output array for (i=n-1; i>=0; i--) { output[count[arr[i].d - 1] - 1] = arr[i]; count[arr[i].d - 1]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to curent digit for (i=0; i<n; i++) arr[i] = output[i];}// A function to do counting sort of arr[] according to// month.void countSortMonth(Date arr[], int n){ Date output[n]; // output array int i, count[12] = {0}; for (i = 0; i < n; i++) count[arr[i].m - 1]++; for (i = 1; i < 12; i++) count[i] += count[i - 1]; for (i=n-1; i>=0; i--) { output[count[arr[i].m - 1] - 1] = arr[i]; count[arr[i].m - 1]--; } for (i = 0; i < n; i++) arr[i] = output[i];}// A function to do counting sort of arr[] according to// year.void countSortYear(Date arr[], int n){ Date output[n]; // output array int i, count[1000] = {0}; for (i = 0; i < n; i++) count[arr[i].y - 2000]++; for (i = 1; i < 1000; i++) count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { output[count[arr[i].y - 2000] - 1] = arr[i]; count[arr[i].y - 2000]--; } for (i = 0; i < n; i++) arr[i] = output[i];}