views:

97

answers:

4

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++?

+2  A: 

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

Kirill V. Lyadvinsky
+10  A: 

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

Armen Tsirunyan
@steven_desu: What non-standard headers?
sth
@steven: `algorithm` and `functional` **are** standard headers as defined by the international C++ standard (see 17.6.1.2 in the current draft). Hand-rolling your own sorting functions is a waste of time. It's error-prone and will most likely yield less efficient code. And what makes you think this is homework? Sometimes people just want to sort arrays and get on with their lives...
FredOverflow
+2  A: 

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.

Erik Noren
+1  A: 

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

http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

動靜能量