In this C++ tutorial, you shall learn how to sort given integer array in ascending or descending order, with examples.
C++ Sort Integer Array
To sort elements of an integer array, call sort() function and pass the beginning and ending of the array as arguments.
By default, sort() function sorts the elements in ascending order. If the required order is descending, pass greater<int>()
as third argument to sort() function. We have mentioned int
for greater()
, since we are sorting integers.
Examples
1. Sort the array {2, 0, 1, 5, 6, 4, 3, -2, -1}
In the following example, we take an integer array initialized with some elements, and find the smallest number of the elements of this array.
main.cpp
#include <iostream>
using namespace std;
int main() {
int x[] = {2, 0, 1, 5, 6, 4, 3, -2, -1}; //integer array
int len = sizeof(x) / sizeof(x[0]); //get array length
sort(x, x + len);
cout << "Sorted Array" << endl;
for (int i = 0; i < len; i++) {
cout << x[i] << "\t";
}
cout << endl;
}
Output
Sorted Array
-2 -1 0 1 2 3 4 5 6
Program ended with exit code: 0
The array is sorted in ascending order.
2. Sort the array {2, 0, 1, 5, 6, 4, 3, -2, -1} in descending order
In the following program, we shall sort the given array in descending order.
main.cpp
#include <iostream>
using namespace std;
int main() {
int x[] = {2, 0, 1, 5, 6, 4, 3, -2, -1}; //integer array
int len = sizeof(x) / sizeof(x[0]); //get array length
sort(x, x + len, greater<int>());
cout << "Sorted Array" << endl;
for (int i = 0; i < len; i++) {
cout << x[i] << "\t";
}
cout << endl;
}
Output
Sorted Array
6 5 4 3 2 1 0 -1 -2
Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned how to sort an integer array in ascending or descending order, with the help of examples.