PAT乙级补充知识:qsort(),结构体排序

推荐阅读原文https://blog.csdn.net/qq_37205425/article/details/84679782
以下内容有修改补充。

PAT乙级补充知识:qsort(),结构体排序

对结构体一级排序

#include <stdio.h>
#include <stdlib.h>

struct node {
	double data;
	int other;
}s[100];

//按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种

int cmp( const void *a ,const void *b)
{
	struct node *c = ( struct node * )a;
	struct node *d = ( struct node * )b;

	return (c->data > d->data) ? 1 : -1;
}

int main()
{
    s[0].data = 1.1;
    s[0].other = 5;
    s[1].data = 2.12;
    s[1].other = 14;
    s[2].data = 1.11;
    s[2].other = 56;
    s[3].data = 5.34;
    s[3].other = 54;
    s[4].data = 4.41;
    s[4].other = 2;

    qsort(s,5,sizeof(s[0]),cmp);

    int i;
    for ( i=0; i<5; i++ ) {
        printf("s[i].data = %.3f s[i].other = %d\n",s[i].data,s[i].other);
    }

    return 0;
}

运行结果:
在这里插入图片描述

对结构体二级排序

#include <stdio.h>
#include <stdlib.h>

struct node{
	int x;
	int y;
}s[100];

//按照x从小到大排序,当x相等时按照y从大到小排序

int cmp( const void *a , const void *b ){
	struct node *c = (struct node *)a;
	struct node *d = (struct node *)b;

	if (c->x != d->x) {
        return c->x - d->x;
	}
	else {
        return d->y - c->y; //从大到小所以d-c
	}
}

int main()
{
    s[0].x = 1;
    s[0].y = 5;
    s[1].x = 2;
    s[1].y = 14;
    s[2].x = 1;
    s[2].y = 56;
    s[3].x = 5;
    s[3].y = 54;
    s[4].x = 4;
    s[4].y = 2;

    qsort(s,5,sizeof(s[0]),cmp);

    int i;
    for ( i=0; i<5; i++ ) {
        printf("s[i].x = %d s[i].y = %d\n",s[i].x,s[i].y);
    }

    return 0;
}

运行结果:
在这里插入图片描述

对结构体三级排序(都是从小到大)

#include <stdio.h>
#include <stdlib.h>

typedef struct item{
	int x,y,z;
} ty;

ty s[105];

//全部按照从小到大排序

int cmp( const void *a , const void *b ){
	ty *c = (ty *)a;
	ty *d = (ty *)b;

	if ( c->x != d->x ) {
        return c->x - d->x;
	}
	else {
        if ( c->y != d->y ) {
            return c->y - d->y;
        }
        else {
            return c->z - d->z;
        }
	}
}

int main()
{
    s[0].x = 1;
    s[0].y = 4;
    s[0].z = 3;
    s[1].x = 1;
    s[1].y = 5;
    s[1].z = 6;
    s[2].x = 1;
    s[2].y = 5;
    s[2].z = 2;
    s[3].x = 5;
    s[3].y = 2;
    s[3].z = 4;
    s[4].x = 4;
    s[4].y = 2;
    s[4].z = 4;

    qsort(s,5,sizeof(s[0]),cmp);

    int i;
    for ( i=0; i<5; i++ ) {
        printf("s[i].x = %d s[i].y = %d s[i].z = %d\n",s[i].x,s[i].y,s[i].z);
    }

    return 0;
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值