三种算法排序学生成绩

使用三种算法对已经给出的文件中的学生成绩排序并且分数相同,同一名次

文件学生信息

冒泡排序

printf("冒泡排序\n");
	for(a=1;a<i;a++){
		for(b=0;b<i-a;b++){
			if(stu[b].score>stu[b+1].score){
				temp=stu[b];
				stu[b]=stu[b+1];
				stu[b+1]=temp;
			}
		}
	}

直接插入排序

	printf("直接插入排序\n");
	for(a=1; a<i; a++)
		if(stu[a].score<stu[a-1].score) {
			temp=stu[a];
			for(b=a-1; b>=0&&stu[b].score>temp.score; --b)
				stu[b+1]=stu[b];
			stu[b+1]=temp;
		}

快速排序

int Partion(struct student stu[],int low,int high) {
	struct student poiv=stu[low];
	while(low<high) {
		while(low<high&&stu[high].score>=poiv.score) --high;
		stu[low]=stu[high];
		while(low<high&&stu[low].score<=poiv.score)  ++low;
		stu[high]=stu[low];
	}
	stu[low]=poiv;
	return low;
}

void quiksort(struct student a[],int low,int high) {
	if(low<high) {
		int poivtpos=Partion(a,low,high);
		quiksort(a,low,poivtpos-1);
		quiksort(a,poivtpos+1,high);
	}
}


	printf("快速排序\n");
	int low,high=i;
	quiksort(stu,1,i);

完整代码

#include<stdio.h>
#include<string.h>
#define MAX 100
typedef struct student {
	char name[8];
	int score;
	int k;
} stu[MAX];

int Partion(struct student stu[],int low,int high) {
	struct student poiv=stu[low];
	while(low<high) {
		while(low<high&&stu[high].score>=poiv.score) --high;
		stu[low]=stu[high];
		while(low<high&&stu[low].score<=poiv.score)  ++low;
		stu[high]=stu[low];
	}
	stu[low]=poiv;
	return low;
}

void quiksort(struct student a[],int low,int high) {
	if(low<high) {
		int poivtpos=Partion(a,low,high);
		quiksort(a,low,poivtpos-1);
		quiksort(a,poivtpos+1,high);
	}
}

int main() {
	struct student stu[MAX];
	char std[50];
	FILE *fp;
	if((fp=fopen("E:\\5.txt","r"))==NULL) {
		printf("Could not open the file!");
	}
	int i=0;
	fgets(std,50,fp);
	while(!feof(fp)) {
		fscanf(fp,"%s%d",stu[i].name,&stu[i].score); //数组存数据
		i++;
	}
	fclose(fp);

	int a,b,j;
	struct student temp;

	printf("冒泡排序\n");
	for(a=1;a<i;a++){
		for(b=0;b<i-a;b++){
			if(stu[b].score>stu[b+1].score){
				temp=stu[b];
				stu[b]=stu[b+1];
				stu[b+1]=temp;
			}
		}
	}


	printf("直接插入排序\n");
	for(a=1; a<i; a++)
		if(stu[a].score<stu[a-1].score) {
			temp=stu[a];
			for(b=a-1; b>=0&&stu[b].score>temp.score; --b)
				stu[b+1]=stu[b];
			stu[b+1]=temp;
		}


	printf("快速排序\n");
	int low,high=i;
	quiksort(stu,1,i);

	printf("姓名\t排名\t成绩\n");
	for(j=0; j<i; j++) {
		printf("%s\t%d\t%d\n",stu[j].name,j+1,stu[j].score);
		while(stu[j+1].score==stu[j].score) {
			printf("%s\t%d\t%d\n",stu[j+1].name,j+1,stu[j+1].score);
			for(j=j+2; j<i; j++) {
				printf("%s\t%d\t%d\n",stu[j].name,j,stu[j].score);
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值