#include <stdio.h>
#include <stdlib.h>
#define N 40
int readscore(int score[]);
void printscore(int score[],int n);
void selectionsort(int a[],int n,int (*compare)(int a,int b));
int Ascending(int a,int b);
int Descending(int a,int b);
void swap(int *x,int *y);
int main()
{
int score[N],n;
int order;
n=readscore(score);
printf("total students are %d\n",n);
printf("Enter 1 to sort in ascending order,\n");
printf("Enter 2 to sort in descending order,\n");
scanf("%d",&order);
printf("Data items in original order\n");
printscore(score,n);
if(order==1)
{
selectionsort(score,n,Ascending);
printf("Data items in ascending order\n");
}
else
{
selectionsort(score,n,Descending);
printf("Data items in descending order\n");
}
printscore(score,n);
return 0;
}
int readscore(int score[])
{
int i=-1;
do{
i++;
printf("Input score(it will be end if you enter a negative number):\n");
scanf("%d",&score[i]);
}while(score[i]>=0); //当输入负数时,结束语句。
return i;
}
void printscore(int score[],int n)
{
int i;
for(i=0;i<n;i++)
{
printf("%4d",score[i]);
}
printf("\n");
}
void selectionsort(int a[],int n,int (*compare)(int a,int b))
{
int i,j,k;
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
{
if((*compare)(a[j],a[k]))k=j;
}
if(k!=i) swap(&a[k],a[i]);
}
}
int Ascending(int a,int b)
{
return a<b;
}
int Descending(int a,int b)
{
return a>b;
}
void swap(int *x,int *y)
{
用函数指针编程实现一个通用的排序函数,既能实现对学生成绩的升序排序,又能实现对学生成绩的降序排序。
最新推荐文章于 2023-04-01 10:26:24 发布