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>.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

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.

Download  Run Code

Output:

7 5 4 3 2

That’s all about sorting an array in descending order in C++.