#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int s[100], n, i;
int cmp(const void *a, const void *b)
{
return(*(int*)b-*(int*)a);
}
int main()
{
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &s[i]);
qsort(s, n, sizeof(s[0]), cmp);
for (i = 0; i < n; i++)
printf("%d ", s[i]);
system("pause");
return 0;
}
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char w[100];
int cmp(const void *a, const void *b)
{
return *(char *)a - *(char *)b;
}
int main()
{
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%c", &w[i]);
qsort(w, n, sizeof(w[0]), cmp);
for (i = 0; i < n; i++)
printf("%c ", w[i]);
system("pause");
return 0;
}
头文件:
#include <algorithm>
using namespace std;
1.默认的sort函数是按升序排。
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。
例如:
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序
又如:
int cmp( const POINT &a, const POINT &b ){
if( a.x < b.x )
return 1;
else
if( a.x == b.x ){
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排