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++?
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.
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.
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>());
}
You can pass custom comparison functor to the std::sort function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With