使用三种算法对已经给出的文件中的学生成绩排序并且分数相同,同一名次
文件学生信息
冒泡排序
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);
}
}
}
}