• Register
100 points
5 1

How to sort in c++

posted May 14 2 min read

In C++ programming,we have in-built sort() function for sorting the elements in ascending order as well as descending order.Although we can use bubble sort,quick sort etc algorithum for sorting but here i am discussing about in-built sort function and how to use it.

Let’s get started!!

Standard Templete Library(STL) in C++ provides sort() function which sorts an array or vector.This function takes three parameters.First parameter is starting of array from where we want an array to be sorted.This points the first element of array.Second parameter is the length upto which we want an sorted array and third parameter is optional,it will use when we want sorting in lexicographically.

By default,sort() function will sort an array in ascending order.

Code1:

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int arr[] = { 2, 5, 7, 3, 6, 86 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    /*Here we take two parameters, the beginning of the
    array and the length n upto which we want the array to
    be sorted*/
    sort(arr, arr + n);
  
    cout << "\nArray after sorting using "
            "in-built sort function is : \n";
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
  
    return 0;
}

Output1:

Array after sorting using in-built sort function is : 
2 3 5 6 7 86 

Now,we will discuss about sorting the array elements in descending order.

Apart from two parameter,we will use greater() function as  third parameter in sort() function.It will put the greater element first in an array.

Code2:

#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    int arr[] = { 2, 5, 7, 3, 6, 86 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    
    sort(arr, arr + n,greater<int>());
  
    cout << "\nArray after sorting in descending order is : \n";
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
  
    return 0;
}

Output2:

Array after sorting in descending order is : 
86 7 6 5 3 2