Hi,
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++?
Hi,
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++?
You can pass custom comparison functor to the std::sort function.
In your code only the first element of the array is set.
now, suppose you have a real array of n integers to sort it in asc. use:
#include <algorithm>
int main()
{
//...
std::sort(array, array+n);
}
to sort it in desc. use
#include <algorithm>
#include <functional>
int main()
{
//...
std::sort(array, array+n, std::greater<int>());
}
HTH
Well first I'm hoping your array assignment was just an error when posting but all your numbers are being assigned to the same memory location. There's nothing to sort.
After that, you can use the sort() function. The example linked shows an easy method for using it. Note that there is a third parameter that's not being used that will specify how to compare the elements. By default if you don't specify the parameter it uses 'less-than' so you get an ascending order sort. Change this to specify 'greater-than' comparator to get a descending order sort.
Generally, you can just swap the two variables in
http://www.cplusplus.com/reference/algorithm/sort/
Change
bool myfunction (int i,int j) { return (i<j); }
to
bool myfunction (int i,int j) { return (j<i); }
you can rename it to something else so that you have two comparison functions to use when the result needs to be ascending or descending.
If the function body has complicated expressions and involves i
and j
multiple times, then it is easier to swap the i
and j
in the parameter list instead of every i
and j
in the body:
bool myfunction (int j,int i) { return (i<j); }
The same goes for