#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct student
{
char name[8];
int score;
};
void insertsort(struct student stu[],int stunum)
{
int i,j;
for(i=2;i<=stunum;i++){
if(stu[i].score<stu[i-1].score){
stu[0]=stu[i];
stu[i]=stu[i-1];
for(j=i-2;stu[0].score<stu[j].score;j--){
stu[j+1]=stu[j];
}
stu[j+1]=stu[0];
}
}
}
int quzhouindex(struct student stu[],int low,int high)
{
stu[0]=stu[low];
int quzhou_value=stu[0].score;
while(low<high)
{
//第一次编译时,结果错误,无限循环,因为我的测试数据最后一个元素为49,和第一个元素相等
//下面条件应为stu[high].score>q大于等于uzhou_value,而非大于 找比枢轴元素小的放在前面
while(low<high && stu[high].score>=quzhou_value)high--;
//刚从外层循环进入时,必定满足low<high。
//但在经历high--后未必满足,到那时不仅会发生错误的比较,甚至可能出现下标越界
stu[low]=stu[high];
while(low<high && stu[low].score<=quzhou_value)low++;//找比枢轴元素大的放在后面
stu[high]=stu[low];
}
stu[low]=stu[0];
return low;
}
void quicksort(struct student stu[],int low,int high)
{
//表长大于1,表长小于等于1的表无需排序
int index;
if(low<high){
index=quzhouindex(stu,low,high);
quicksort(stu,low,index-1);
quicksort(stu,index+1,high);
}
}
void printstu(struct student stu[],int stunum)
{
int j=1;
for(int i=stunum; i>0; i--)
{
if(i!=stunum && stu[i].score!=stu[i+1].score)
{
j++;
}
printf("%2d %4d %8s\n",j,stu[i].score,stu[i].name);
}
}
int main()
{
int stunum;
struct student stu[MAXSIZE];
printf("请输入学生人数:\n");
scanf("%d",&stunum);
for(int i=1; i<=stunum; i++)
{
scanf("%d %s",&stu[i].score,&stu[i].name);
}
//直接插入排序
//insertsort(stu,stunum);
printstu(stu,stunum);
//快速排序
quicksort(stu,1,stunum);
printstu(stu,stunum);
return 0;
}
/*
测试数据:
8
49 Abc
38 Bbc
65 Cbc
97 Dbc
76 Ebc
13 Fbc
27 Gbc
49 Hbc
*/
直接插入排序+快速排序 c(实验课作业)
最新推荐文章于 2024-07-25 17:33:54 发布