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

C++Server Side ProgrammingProgramming

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
raja
Published on 29-Mar-2019 15:12:41
Advertisements