Sort function in C++


Sort in C++

        C++ has an Inbuilt function for sorting. You can sort both in ascending as well as in descending order. The sort function is very useful in array manipulations programs.

        You just need to give the array name and its size and the STL command does the job

The syntax is very simple as shown below.

For ascending order

sort(array_name, array_name + array_size);


For descending order

sort(array_name, array_name + array_size, greater<int>());


This example would help you to understand better

array name a = {5,3,1,2,6}

array size n = 5


ascending order

sort(a, a+n);


output: 1 2 3 5 6


descending order

sort(a, a+n, greater<int>());


output: 6 5 3 2 1


    Checkout


Write a program to Sort the array in ascending order


Code

#include <bits/stdc++.h>

using namespace std;


int main(){

    

    int n;    

    cin>>n;

    

    int a[n];               

    for(int i=0;i<n;i++){

        cin>>a[i];

    } 


    sort(a, a+n);           //inbuilt sort function

    

   for(int i=0;i<n;i++){

       cout<<a[i]<<" ";

   } 

   

   return 0;

}


Input

5

9 4 3 8 2


Output

2 3 4 8 9 

Post a Comment

0 Comments