文章

19

粉丝

0

获赞

138

访问

2.9k

头像
成绩排序 C语言题解:qsore排序
P1151 清华大学上机题
发布于2026年3月13日 09:36
阅读数 209

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

typedef struct cj{
	char name[100];
	int score;
}cj;
int sign;

int compare(const void* a, const void* b){
	const cj *aa=(const cj*)a;
	const cj *bb=(const cj*)b;
	return sign==1 ? aa->score-bb->score : bb->score-aa->score;
}

int main(){
	int n;
	while(~scanf("%d", &n)){
		scanf("%d", &sign);
		cj *sc=(cj*)calloc(n, sizeof(cj));

		for(int i=0; i<n; i++){
			scanf("%s %d", sc[i].name, &sc[i].score);
		}
		qsort(sc, n, sizeof(cj), compare);
		for(int i=0; i<n; i++){
			printf("%s %d\n", sc[i].name, sc[i].score);
		}
	}

	
	return 0;
}

 

登录查看完整内容


登录后发布评论

1 条评论
贺生旭
2026年3月15日 14:46

两个问题:

      1、qsort是不稳定排序,需要加上输入顺序的id一起排序

      2、使用malloc之后程序结束前要free释放内存,防止程序崩溃

 

赞(1)
回复给: