
403 views
C++ Program To Sort An Array In Descending Order
You can sort an array in descending order in C++ using the standard library function std::sort. However, since std::sort sorts in ascending order by default, you need to provide a custom comparison function to sort in descending order. Here’s an example of how to do this:
#include <iostream>
#include <algorithm>
bool compareDescending(int a, int b) {
return a > b; // Compare in descending order
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n, compareDescending);
std::cout << "Array sorted in descending order: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
In this code:
- We include the necessary headers
<iostream>and<algorithm>. - We define a custom comparison function
compareDescending, which returnstrueifashould come beforebin the sorted order (i.e., ifais greater thanbfor descending order). - In the
mainfunction, we define an integer arrayarrand determine its sizen. - We use
std::sortto sort the arrayarrin descending order by passing thecompareDescendingfunction as the third argument tostd::sort. - Finally, we print the sorted array in descending order.
After running this program, the arr array will be sorted in descending order, as specified by the custom comparison function.