要求:对动态数组中n个学生的数据,按成绩升序实现选择排序。
#include<stdio.h>
#include<stdlib.h>
struct student
{
int id;
char name[20];
float score;
};
struct student *input(int n);
void sort(struct student *pstu,int n);
void output(struct student stu[],int n);
void swap(struct studdent *p1,struct studdent *p2);
int main()
{
struct student *pstu;
int n;
printf("请输入学生人数:");
scanf("%d",&n);
printf("请输入学生学号、姓名、成绩:");
pstu=input(n);
sort(pstu,n);
output(pstu,n);
free(pstu);
return 0;
}
//输入
struct student *input(int n)
{
int i;
struct student *pstu=(struct student *)calloc(n,sizeof(struct student));
for(i=0;i<n;i++)
scanf("%d %s %f",&pstu[i].id,pstu[i].name,&pstu[i].score);
return pstu;
}
//排序
void sort(struct student *pstu,int n)
{
struct student *pmin,*p;
int i;
for(i=0;i<n-1;i++)
{
pmin=pstu+i;
for(p=pmin+1;p<pstu+n;p++)
if(p->score < pmin->score)
pmin=p;
if(pmin!=pstu+i)
swap(pmin,pstu+i);
}
}
//交换
void swap(struct studdent *p1,struct studdent *p2)
{
struct student tmp;
tmp = p1;
p1 = p2;
p2 = tmp;
}
//输出
void output(struct student *pstu,int n)
{
struct student *p;
p=pstu;
while(p<pstu+n)
{
printf("%d %s %f",p->id,p->name,p->score);
p++;
}
}