qsort函数辅助函数compare函数的编写

qsort的第四个参数,辅助函数compare的关于不同排序对象的不同写法:

一、对int类型数组排序

int num[100];
int compare(const void *a, const void *b)
{
  return *(int *)a - *(int *)b;
}

 

二、对char类型数组排序(同int类型)

char word[100];
int compare(const void *a, const void *b)
{
  return *(char *)a - *(char *)b;
}

 

三、对double类型数组排序

double array[100];
int compare(const void *a, const void *b)
{
  return *(double *)a > *(double *)b ? 1 : -1;
}

注意qsort第三个参数是sizeof(array[0])。

四、对结构体一级排序

typedef struct node
{
    double data;
    int other;
}Node;
array[100];

int compare(const void *a, const void *b)
{
    return ((Node *)a)->data > ((Node *)b)->data ? 1 : -1;
}

 

五、对结构体二级排序

typedef struct node
{
    int x;
    int y;
}Node;
Node array[100];
//按照x从小到大排序,当x相等时按照y从大到小排序 
int compare(const void *a, const void *b)
{
    Node *p1 = (Node *)a;
    Node *p2 = (Node *)b;
    if (p1->x != p2->x)
        return p1->x - p2->x;
    else
        return p1->y - p2->y;
}

 

六、对字符串进行排序

typedef struct node
{
    int other;
    char string[100];
}Node;
Node array[100];
//按照结构体中字符串string的字典顺序排序 
int compare(const void * a, const void * b)
{
    return strcmp(((Node *)a)->string, ((Node *)b)->string);

 

转载于:https://www.cnblogs.com/ray-coding-in-rays/p/6216507.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值