#include <iostream>
#include <algorithm>
using namespace std;
bool compare(int a, int b) {
return a > b;
}
int main() {
int arr[] = {5, 2, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n, compare);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
- Include necessary libraries:
<iostream>
for input/output and <algorithm>
for sort
. - Use the
namespace std
to avoid writing std::
before standard library functions. - Create a function
compare
that takes two integers a
and b
and returns true
if a
is greater than b
. - In the
main
function:- Declare an array
arr
with values {5, 2, 9, 1, 5}
. - Calculate the size of the array
n
. - Use
sort
from the <algorithm>
library to sort the array in descending order, using the compare
function for the comparison logic. - Print the sorted array elements using a
for
loop.
- The program outputs the sorted array elements in descending order:
9 5 5 2 1
.