Home » C++ STL

Sort an array in descending order using sort() function in C++ STL

C++ STL - sort() function Example: In this article, we are going to learn how to sort array elements in Descending Order using sort() function of C++ - STL?
Submitted by IncludeHelp, on January 03, 2018

Given an array and we have to sort the elements in Descending Order using C++ STL sort() function.

sort() function

It is a built-in function of algorithm header file it is used to sort the containers like array, vectors in specified order.

Reference: http://www.cplusplus.com/reference/algorithm/sort/

To sort elements in Descending order, we need to pass a function as third parameter, we can use greater<>() function.

This function creates comparison between the elements and puts the greater (largest element) first and then we can get descending order sorted elements.


sort(first, last, camp/function);

first - is the index (pointer) of first element from where we want to sort the elements.
last - is the last index (pointer) of last element.
camp/function - a comparison function that will create comparison between the elements.


    Array: 10, 1, 20, 2, 30

    Sorted Array: 30, 20, 10, 2, 1

C++ program:

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

int main(){
	//declare and define an array
	int arr[]={10, 1, 20, 2, 30};
	//size of the array
	//total size/size of an element
	int size = sizeof(arr)/sizeof(int);
	//calling sort() to sort array elements
	sort(arr, arr+5, greater<>());
	//printing sorted elements
	cout<<"Sorted elements are: ";
	for(int i=0; i<size; i++)
		cout<<arr[i]<<" ";
	return 0;


Sorted elements are: 30 20 10 2 1 

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.