推荐阅读原文: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;
}
运行结果: