利用qsort给结构体按三级排序
最小年龄的3个职工
http://www.nowcoder.com/questionTerminal/a9fa482eb05149cdbad88689e3cb5f66
#include <stdio.h> #include<stdlib.h> #include<string.h> typedef struct{ int id; char name[20]; int age; }Staff,*snode; int cpr(const void * a,const void* b) { snode x = (snode) a; snode y = (snode) b; if(x->age != y->age) return x->age - y->age; else if(x->id != y->id) return x->id - y->id; else return strcmp(x->name,y->name); } int main() { int n; scanf("%d",&n); int min = n>3?3:n; snode s = (snode)malloc(sizeof(Staff)*n); for(snode i = s;i<s+n;i++) scanf("%d %s %d",&i->id,i->name,&i->age); qsort(s,n,sizeof(s[0]),cpr); for(snode i= s;i<s+min;i++) printf("%d %s %d\n",i->id,i->name,i->age); return 0; }