C++ qsort在"iostream" c在头文件stdlib.h中,strcmp在string.h中。下列例子默认从小到大排序即(a>b返回>0),反之从小到大排序
1、对int类型数组排序
int num[100]; int cmp ( const void *a , const void *b ) { return *(int *)a - *(int *)b; } qsort(num,100,sizeof(num[0]),cmp);
2、对char类型数组排序(同int类型)
char strs[100]; int cmp( const void *a , const void *b ) { return *(char *)a - *(int *)b; } qsort(strs,100,sizeof(strs[0]),cmp);
3、对double类型数组排序(特别要注意)
double dbs[100]; int cmp( const void *a , const void *b ) { return *(double *)a > *(double *)b ? 1 : -1; } qsort(dbs,100,sizeof(dbs[0]),cmp);
4、对结构体一级排序
struct d { int a; }arr[100] int cmp( const void *a ,const void *b) { return (*(d *)a)->a > (*(d *)b)->b ? 1 : -1; } qsort(arr,100,sizeof(arr[0]),cmp);
5、对结构体二级排序
struct d { int x; int y; }arr[100]; //按照x从小到大排序,当x相等时按照y从大到小排序 int cmp( const void *a , const void *b ) { struct d *c = (d *)a; struct d *e = (d *)b; return c->x != e->x?c->x - e->x:return e->y - c->y; } qsort(d,100,sizeof(d[0]),cmp);
6、对字符串进行排序
struct dict{ char str[100]; }dicts[100] int cmp ( const void *a , const void *b ) { return strcmp( (*(dict *)a)->str , (*(dict *)b)->str ); } qsort(dicts,100,sizeof(dicts[0]),cmp);