I have this array:
array[0] = 18;
array[1] = -10;
array[2] = 2;
array[3] = 4;
array[4] = 开发者_C百科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++?
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.
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.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[])
{
int num[10]={18,-10,2,4,6,-12,-8,-6,13,-1};
int temp;
cout << "Ascending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
cout << num[i] << "\n";
}
cout << "\nDescending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]<num[j])
{
temp=num[j];
num[j]=num[i];
num[i]=temp;
}
}
cout << num[i] << "\n";
}
return 0;
}
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/
精彩评论