Sort an array in descending order in C++
This post will discuss how to sort an array in descending order in C++.
To sort an array in reverse/decreasing order, you can use the std::sort
algorithm provided by STL. It sorts the elements of a container in the range pointed by the specified iterators using a comparator. The default comparator used is std::less<>
, which sorts the container in ascending order using operator<
. We can use std::greater<>
to sort in descending order, which delegates the call to operator>
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <algorithm> int main() { int arr[] = { 3, 5, 2, 4, 7 }; std::sort(std::begin(arr), std::end(arr), std::greater<>()); // pass the template argument <int> to `std::greater` before C++14; // otherwise, the code won't compile for (int const &i: arr) { std::cout << i << ' '; } return 0; } |
Output:
7 5 4 3 2
We can also pass a custom comparator to the sort function. The custom comparator should be a binary predicate that compares its two arguments and return a bool
that determines whether the first argument goes before the second argument in the sorted array. We can pass the custom comparator to the sort()
function in many ways:
1. We can use an instance of a class implementing the ()
operator as a comparison function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <algorithm> struct comp { bool operator()(int const &i, int const &j) const { return i > j; } }; int main() { int arr[] = { 3, 5, 2, 4, 7 }; std::sort(std::begin(arr), std::end(arr), comp()); // code to print the array return 0; } |
Output:
7 5 4 3 2
2. We can also use a binary function that accepts two elements as arguments and returns true if the first argument is less than the second argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> int comp(int const &i, int const &j) { return i > j; } int main() { int arr[] = { 3, 5, 2, 4, 7 }; std::sort(std::begin(arr), std::end(arr), comp); // code to print the array return 0; } |
Output:
7 5 4 3 2
3. With C++11, we can even pass a lambda to the std::sort
function to define the ordering.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <algorithm> int main() { int arr[] = { 3, 5, 2, 4, 7 }; std::sort(std::begin(arr), std::end(arr), [](auto const &i, auto const &j) { return i > j; }); // code to print the array return 0; } |
Output:
7 5 4 3 2
That’s all about sorting an array in descending order in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)