题解 | #归并排序#
成绩排序
http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
qsort
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ int index; char name[20]; int grade; } Na; int myCompareH2L(const void *item1, const void *item2) { Na *p1 = (Na *) item1, *p2 = (Na *) item2; if(p1->grade != p2->grade){ return p2->grade - p1->grade; } else{ return p1->index - p2->index; } } int myCompareL2H(const void *item1, const void *item2) { Na *p1 = (Na *) item1, *p2 = (Na *) item2; if(p1->grade != p2->grade){ return p1->grade - p2->grade; } else{ return p1->index - p2->index; } } int main() { int num, k; while(scanf("%d%d", &num, &k) != EOF){ Na Name_list[num]; int i; for(i = 0; i < num; i++){ scanf("%s", Name_list[i].name); scanf("%d", &Name_list[i].grade); Name_list[i].index = i; } if(k == 0){ qsort(Name_list, num, sizeof(Na), myCompareH2L); } else if(k == 1){ qsort(Name_list, num, sizeof(Na), myCompareL2H); } for(i = 0; i < num; i++){ printf("%s %d\n", Name_list[i].name, Name_list[i].grade); } } }