
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
How to sort an array of dates in C/C++?
Suppose we have an array of dates. Here we will see how to sort then using C or C++ code. The dates are stored in a class (struct can be used in C also). We will use the sort function of the C++ STL. For comparing dates, we have to write our own compare function that will be used in the sort function. Let us see the example to get better view.
Example
#include<iostream> #include<iostream> #include<algorithm> using namespace std; class Date { public: int d, m, y; }; bool compare(const Date &date1, const Date &date2){ if (date1.y < date2.y) return true; if (date1.y == date2.y && date1.m < date2.m) return true; if (date1.y == date2.y && date1.m == date2.m && date1.d < date2.d) return true; return false; } void sortDateArray(Date arr[], int n) { sort(arr, arr+n, compare); } int main() { Date arr[] = {{20, 1, 2017}, {25, 3, 2010}, { 3, 12, 1956}, {18, 10, 1982}, {19, 4, 2011}, { 9, 7, 2013}}; int n = sizeof(arr)/sizeof(arr[0]); sortDateArray(arr, n); cout << "Sorted dates are" << endl; for (int i=0; i<n; i++) { cout << arr[i].d << " " << arr[i].m << " " << arr[i].y << endl; } }
Output
Sorted dates are 3 12 1956 18 10 1982 25 3 2010 19 4 2011 9 7 2013 20 1 2017
- Related Articles
- Sort an array of dates in PHP
- How to sort an array in C#?
- How to use std::sort to sort an array in C++
- How to sort an Array using STL in C++?
- Sort an Array in C++
- PHP program to sort dates given in the form of an array
- Sort an Array of string using Selection sort in C++
- C program to sort an array in an ascending order
- C program to sort an array by using merge sort
- C# program to sort an array in descending order
- C program to sort an array in descending order
- Sort an array according to count of set bits in C++
- Sort an array of strings according to string lengths in C++
- Minimum number of swaps required to sort an array in C++
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm

Advertisements