How to sort an array in descending order using sort() in c++?

The C++ STL function sort() by default sorts the array in ascending order. If we want to sort array in descending order using sort(), we need to use a Comparator Function.

Syntax

sort(first index address, last index address, Comparator function);

Sort Array in Descending Order Using sort()

We can use the inbuilt greater<type>() function to arrange array in descending order.

greater<type>() compares the array elements using > (greater than) operator instead of default < (less than) operator.

#include<iostream>
#include<algorithm>
using namespace std;

int main()
{	
	int a[] = {1,2,3,4,5,6,7,8,9,10};
	int n = sizeof(a)/sizeof(a[0]);
	
	cout<<"Before Sort: ";
	for(int i=0;i<n;++i){
		cout<<a[i]<<' ';
	}
	cout<<endl;
	
	sort(a,a+n,greater<int>());
	
	cout<<"After Sort: ";
	for(int i=0;i<n;++i){
		cout<<a[i]<<' ';
	}
	cout<<endl;
}

Output

Before Sort: 1 2 3 4 5 6 7 8 9 10
After Sort: 10 9 8 7 6 5 4 3 2 1

Sorting in Descending Ordering Using User-defined Comparator Function

The Comparator function accepts 2 arguments and their data type is the same as the data type of array elements.

Syntax

// dataType is the datatype of element stored in array
bool ComparatorFunction(dataType v1, dataType v2){
     ...
     ...
}


If the comparator functions return true, then the first argument ( v1 ) will appear first after sorting the array otherwise the second argument ( v2 ) will appear first.

See the following example for better understanding.

#include<iostream>
#include<algorithm>
using namespace std;

bool SORT(int v1,int v2){
	return v1>v2;
}

int main()
{	
	int a[] = {1,2,3,4,5,6,7,8,9,10};
	int n = sizeof(a)/sizeof(a[0]);
	
	cout<<"Before Sort: ";
	for(int i=0;i<n;++i){
		cout<<a[i]<<' ';
	}
	cout<<endl;
	
	sort(a,a+n,SORT);
	
	cout<<"After Sort: ";
	for(int i=0;i<n;++i){
		cout<<a[i]<<' ';
	}
	cout<<endl;
}

Output

Before Sort: 1 2 3 4 5 6 7 8 9 10
After Sort: 10 9 8 7 6 5 4 3 2 1

In the above code, we used the condition v1>v2 in the Comparator Function. If the Comparator function returns true then it means the first parameter will appear before the second parameter in the sorted list.
Hence, if v1>v2 is true, then the function will return true and v1 will appear before v2 after sorting.
If v1>v2 is false, then the function will return false and v2 will appear before v1 after sorting.

Comparator function is very useful, especially in sorting class and structure type list.

How it works?

It’s working is very simple.
The sort() functions uses this comparator function for comparing any 2 values of the array.

For example, in sorting algorithms, we compare elements as x < y or x > y. The sort() function uses Comparator function for comparing array elements, Comparator(x,y).

Reference

https://en.cppreference.com/w/cpp/algorithm/sort

Leave a Comment

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