1.qsort 功 能: 使用快速排序例程进行排序
用 法: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));
各参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针
[color=red]这个函数还可以对结构体进行二级排序噢[/color]
具体案例:
当cmp返回的值>0,则a > b,当cmp返回的值< 0, 则a < b;
这里的代码是按照从小到大的升序排序。
同理,用C++的STL函数sort也可以做到。
而sort只要写sort(haha, haha+n, cmp);即可
如
用 法: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));
各参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针
[color=red]这个函数还可以对结构体进行二级排序噢[/color]
具体案例:
struct Q
{
int li, wi;
}haha[N];
int cmp( const void *a , const void *b ) //qsort 的配对配套使用
{
struct Q *c = (Q *)a;
struct Q *d = (Q *)b;
if(c->li != d->li) return c->li - d->li;
else return c->wi - d->wi;
}
qsort(haha, n, sizeof(haha[0]), cmp);
当cmp返回的值>0,则a > b,当cmp返回的值< 0, 则a < b;
这里的代码是按照从小到大的升序排序。
同理,用C++的STL函数sort也可以做到。
而sort只要写sort(haha, haha+n, cmp);即可
如
struct star
{
int x, y;
}S[N];
bool cmp(star a, star b)
{
if (a.x != b.x) return a.x < b.x;
else return a.y < b.y;
}
sort(S+1, S + n + 1, cmp);

被折叠的 条评论
为什么被折叠?



