how to sort in descending order c++

To sort an array in descending order in C++, you can use the sort() function from the <algorithm> library. Here are the steps to do it:

  1. Include the necessary header file: cpp #include <algorithm>

  2. Create an array or a vector that you want to sort: cpp int arr[] = {5, 2, 8, 1, 9}; int n = sizeof(arr) / sizeof(arr[0]);

  3. Use the sort() function with a lambda function as the third argument: cpp std::sort(arr, arr + n, [](int a, int b) { return a > b; });

In the lambda function, a and b represent two elements being compared. The expression a > b returns true if a is greater than b, which will sort the array in descending order.

  1. Print the sorted array: cpp for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; }

This loop will iterate over the sorted array and print each element.

Here's the complete code example:

#include <iostream>
#include <algorithm>

int main() {
    int arr[] = {5, 2, 8, 1, 9};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::sort(arr, arr + n, [](int a, int b) { return a > b; });

    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

When you run this code, it will output:

9 8 5 2 1

This means the array has been sorted in descending order. The sort() function rearranges the elements in the array based on the comparison function provided, sorting them from largest to smallest in this case.