How to use std::sort to sort an array in C++


In programming language, sorting is a basic function which is applied to data to arrange these data is ascending or descending data. In C++ program, there is a function std::sort() for sorting the array.

sort(start address, end address)

Here,

Start address => The first address of the element.
Last address => The address of the next contiguous location of the last element of the array.

Example Code

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
void display(int a[]) {
   for(int i = 0; i < 5; ++i)
   cout << a[i] << " ";
}
int main() {
   int a[5]= {4, 2, 7, 9, 6};
   cout << "\n The array before sorting is : ";
   display(a);
   sort(a, a+5);
   cout << "\n\n The array after sorting is : ";
   display(a);
   return 0;
}

Output

The array before sorting is : 4 2 7 9 6

The array after sorting is : 2 4 6 7 9

Updated on: 30-Jul-2019

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements