Sort in C++ STL

About Sorting in STL

Sorting is defined as arranging the data in a particular order, which can be increasing , decreasing or in any specific way. Sorting in STL is done by inbuilt function sort().

sorting in stl

Syntax of Sort() :

sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

The function doesn’t produce a result. Just the items/elements from the first to the last iterations  are updated. The third parameter, comp, must be a function that establishes the hierarchy of the components to be sorted in. If nothing else is supplied, the sorting happens in ascending order.

Example of Sorting in Ascending Order :

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    vector arr;
    arr.push_back(34);
    arr.push_back(70);
    arr.push_back(20);
    arr.push_back(56);
    arr.push_back(1);
    
     cout<<"The element of array before sorting : ";
    for(int i=0;i < arr.size();i++){
         cout<< arr[i]<<" ";
    }
    cout<< endl;
    // sort function to sorting the elements
    sort(arr.begin(), arr.end());   
    cout<<"The element of array after sorting : ";
    for(int i=0;i < arr.size();i++){
         cout<< arr[i]<<" ";
    }
   
    return 0;
}

Output :

The element of array before sorting : 34 70 20 56 1 
The element of array after sorting : 1 20 34 56 70 

In the above program, we take the array and used sort function to sort the elements in ascending order as comparator is not used , by default elements are arranged in ascending order.

Example of Sorting in Descending Order:

Run
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

int main() {
    vector arr;
    arr.push_back(34);
    arr.push_back(70);
    arr.push_back(20);
    arr.push_back(56);
    arr.push_back(1);
    
     cout<<"The element of array before sorting : ";
    for(int i=0;i< arr.size();i++){
         cout<< arr[i]<<" ";
    }
    cout<());   
    cout<<"The element of array after sorting : ";
    for(int i=0;i< arr.size();i++){
         cout<< arr[i]<<" ";
    }
   
    return 0;
}

Output :

The element of array before sorting : 34 70 20 56 1 
The element of array after sorting : 70 56 34 20 1

In the above program, we take the array and used sort function to sort the elements in decreasing  order as greater<int>() comparator is used to sort the elements in decreasing order

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription