c 语言 结构体多级排序,在c中怎样用qsort对结构体数组进行多级排序

匿名用户

1级

2016-12-08 回答

#include 

#include 

struct st_test

{

int cat;

char caTrain[ 100 ];

double plane;

float  tree;

};

int cmp( const void *arg1, const void *arg2 );

int

main( void )

{

int i = 0;

struct st_test stArr[] = {

{ 2, "defghi", 5.2, 6.7 },

{ 2, "aefghi", 5.0, 6.9 },

{ 1, "aefghi", 5.1, 6.0 },

{ 1, "aefghi", 5.9, 5.0 },

{ 3, "elflfg", 9.0, 2.0 },

{ 3, "elflfg", 9.0, 1.0 }

};

qsort( stArr, 6, sizeof( struct st_test ), cmp );

for( i = 0; i 

{

printf( "%2d %8s %3.1lf %3.1f\n", stArr[ i ].cat, stArr[ i ].caTrain,

stArr[ i ].plane, stArr[ i ].tree );

}

return 0;

}

int

cmp( const void *arg1, const void *arg2 )

{

static const double DSTDZERO = 0.0000001;

static const float  FSTDZERO = 0.0000001;

struct st_test *stArg1 = ( struct st_test * )arg1;

struct st_test *stArg2 = ( struct st_test * )arg2;

if( stArg1->cat != stArg2->cat )

return  stArg1->cat > stArg2->cat ? 1 : -1;

else if( strcmp( stArg1->caTrain, stArg2->caTrain ) != 0 )

return -strcmp( stArg1->caTrain, stArg2->caTrain );

else if( !( ( stArg1->plane - stArg2->plane >= -DSTDZERO ) && ( stArg1->plane - stArg2->plane <= DSTDZERO ) ) )

{

if( stArg1->plane - stArg2->plane 

return 1;

if( stArg1->plane - stArg2->plane > DSTDZERO )

return -1;

}

else if( !( ( stArg1->tree - stArg2->tree >= -FSTDZERO ) && ( stArg1->tree - stArg2->tree <= FSTDZERO ) ) )

{

if( stArg1->tree - stArg2->tree 

return -1;

if( stArg1->tree - stArg2->tree > FSTDZERO )

return 1;

}

return 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值