在常用算法总排序是最常用的算法之一!而快排在c 的 stdlib库中是有现成的封装对于我们写算法是提供了方便之处的!
一 、对int类型数组排序
int cmp ( const void *a , const void *b )
{
return *(int *)a - *(int *)b;
}
qsort(arry, n, sizeof(arry[0]), cmp);
qsort(指向一个要排序数组的首地址
, 指要排序数组的元素个数
, 指每个元素的大小
, cmp);
这个是一个从大到小的排序如果要从小到大排序可以讲cmp函数改为如下:
int cmp(constvoid *a,constvoid *b)
{
return*(int *)a - *(int *)b;
}
二、对char类型数组排序(同int类型)
char word[100];
int cmp( const void *a , const void *b )
{
return *(char *)a - *(int *)b;
}
qsort(word,100,sizeof(word[0]),cmp);
三、对double类型数组排序
double in[100];
return *(double *)a > *(double *)b ? 1 : -1;
qsort(in,100,sizeof(in[0]),cmp);
四、对结构体一级排序
struct sample
double data;
int other;
}s[100]
//按照data的值从小到大将结构体排序
int cmp( const void *a ,const void *b)
return (*(sample *)a).data > (*(sample *)b).data ? 1 : -1;
qsort(s,100,sizeof(s[0]),cmp);
五、对结构体二级排序
int x;
int y;
}s[100];
//按照x从小到大排序,当x相等时按照y从大到小排序
struct sample *c = (sample *)a;
struct sample *d = (sample *)b;
if(c->x != d->x) return c->x - d->x;
else return d->y - c->y;
六、对字符串进行排序
int data;
char str[100];
//按照结构体中字符串str的字典顺序排序
int cmp ( const void *a , const void *b )
return strcmp( (*(sample *)a)->str , (*(sample *)b)->str );