This post will discuss how to sort an array in ascending order in C++.

To sort an array in natural/increasing order, you can use the std::sort algorithm provided by STL. It sorts the elements of a container in the range pointed by the specified iterators. Since iterators are nothing but a generalization of pointers, you can pass the pointer to the first element of the array and (1+) the last element of the array for sorting the complete C-style array.

Download  Run Code

Output:

2 3 4 5 7

 
It is worth noting that std::sort doesn’t produce a stable sort. That means the relative order of equal elements will not be preserved in the sorted sequence. The recommended approach to getting a stable sort is to use the std::stable_sort algorithm.

 
Also, above code requires you to know the size of the array in advance. One can skip that in C++11 by using new std::begin and std::end functions, which are overloaded for C-style arrays:

Download  Run Code

 
Note that you can’t use std::begin or std::end inside a function, taking an array as a parameter. For instance, the following code snippet will not compile.

Download  Run Code

Compilation Error:

prog.cpp: In function ‘void sort(int*)’:
prog.cpp:5:26: error: no matching function for call to ‘begin(int*&)’
  std::sort(std::begin(arr), std::end(arr));

 
This is because std::begin and std::end works with an actual array rather than a pointer. But when you call the sort() function, what gets passed isn’t the complete array but a pointer to the first element of the array. So, you need to pass the array by reference to a function template, as shown below:

Download  Run Code

 
Finally, this post is incomplete without talking about std::array introduced with C++11. The following C++ program demonstrates it:

Download  Run Code

That’s all about sorting an array in ascending order in C++.