Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort C++ array in ASC and DESC mode?

I have this array:

array[0] = 18;
array[1] = -10;
array[2] = 2;
array[3] = 4;
array[4] = 6;
array[5] = -12;
array[6] = -8;
array[7] = -6;
array[8] = 4;
array[9] = 13;

how do I sort the array in asc/desc mode in C++?

like image 228
cpp_best Avatar asked Oct 24 '10 12:10

cpp_best


People also ask

How do you sort an array in ascending and descending?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.

How do you sort an array in ascending order?

Example: Sort an Array in Java in Ascending Order Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.


2 Answers

To sort an array in ascending, use:

#include <algorithm>

int main()
{
   // ...
   std::sort(array, array+n); // where n is the number of elements you want to sort
}

To sort it in descending, use

#include <algorithm>
#include <functional>  

int main()
{
   // ...
   std::sort(array, array+n, std::greater<int>());
}
like image 152
Armen Tsirunyan Avatar answered Oct 14 '22 18:10

Armen Tsirunyan


You can pass custom comparison functor to the std::sort function.

like image 2
Kirill V. Lyadvinsky Avatar answered Oct 14 '22 18:10

Kirill V. Lyadvinsky