Sort array using inbuilt sort function in decreasing order
To sort an array in C++ in decreasing order using the inbuilt sort
function, you need to follow these steps:
Include the necessary header file: Begin by including the
<algorithm>
header file, which contains thesort
function.Create an array: Declare and initialize an array with the elements you want to sort.
Specify the range: Pass the starting and ending iterators of the array to the
sort
function. This specifies the range of elements to be sorted.Specify the comparison function: By default, the
sort
function sorts the elements in ascending order. To sort in descending order, you need to specify a comparison function that compares the elements in reverse order.Define the comparison function: Create a comparison function that takes two elements as parameters and returns
true
if the first element should appear before the second element in the sorted order. Otherwise, it should returnfalse
. In this case, the function should returntrue
if the first element is greater than the second element.Call the sort function: Finally, call the
sort
function with the specified range and comparison function.
Here is an example code snippet that demonstrates sorting an array in decreasing order using the sort
function:
#include <algorithm>
#include <iostream>
bool compare(int a, int b) {
return a > b;
}
int main() {
int arr[] = {5, 2, 8, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n, compare);
std::cout << "Sorted array in decreasing order: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
In this example, the array {5, 2, 8, 1, 9}
is sorted in decreasing order using the sort
function and the compare
function. The output will be Sorted array in decreasing order: 9 8 5 2 1
.