How to sort an array in descending order in C++

Sorting a sequence is a problem of great importance in computer science and software development. This article describes the methods to sort both a normal array and the STL array container in descending order.

This article covers only the basic principles for sorting in descending order using the std::sort() of STL. However, these ideas can be used in custom sorting algorithms.

The std::sort() function:

The std::sort () function takes two compulsory arguments and an optional argument. The first two arguments are the iterators (or pointers in the case of a normal array) of the range. The third argument is an argument of type std::functional<bool(T, T)> where T is the object’s datatype stored in the array.

For simplicity, we shall consider T to be an integer.

The syntax for the function is:

std::sort(start pointer, end pointer, functional argument)

This function sorts the range [start, end).

The functional argument can take in function pointers, functionals, and lambda expressions as input.

The elements are sorted as per the functional object.

Sorting an array using std::greater:

The default value of the third argument is a std::less<> object. We can sort the array in descending order using the std::greater functional.

The following code illustrates this:

#include <iostream>
#include <algorithms>
int main()
{
  
  int a[10];
  for (int i = 0; i < 10; i++)
  {
    std::cin >> a[i];
  }
  std::sort(a, a + 10, std::greater<int>{}); // a is the pointer to first object
  std::cout << "The sorted array is: ";
  for (int g : a)
    std::cout << g << " ";
  std::cout << std::endl;
}

Output:

2 5 8 6 4 3 1 7 9 10
The sorted array is: 10 9 8 7 6 5 4 3 2 1

Sorting by changing the order of iterators:

The std::sort() function sorts the elements based on their iterators. Basically, it sorts the elements in ascending order in the provided iterator range.

We can manipulate this to sort in descending order by providing the first argument as an iterator to the last element and the second as an iterator before the first element.

For the standard array container, this can be done with the reverse iterator which can be obtained with rbegin() and rend() methods. However, this won’t work with pointer-based normal arrays because the internal implementation of std::sort() uses the addition of the iterator which will lead to out-of-bound in the case of pointers.

The following code illustrates the point:

#include <iostream> 
#include <algorithms>
int main()
{
std::array<int, 10> a;
for (int i = 0; i < 10; i++)
{
std::cin >> a[i];
}
std::sort(a.rbegin(),a.rend()); // a is the pointer to first object
std::cout << "The sorted array is: ";
for (int g : a)
std::cout << g << " ";
std::cout << std::endl;
}

The output of the code is the same as the above one.

Leave a Reply

Your email address will not be published. Required fields are marked *