如有不对,不吝赐教
进入正题:
Excel可以对一组纪录按任意指定列排序。现请编写程序实现类似功能。
输入格式:
输入的第一行包含两个正整数N(≤10
5
) 和C,其中N是纪录的条数,C是指定排序的列号。之后有 N行,每行包含一条学生纪录。每条学生纪录由学号(6位数字,保证没有重复的学号)、姓名(不超过8位且不包含空格的字符串)、成绩([0, 100]内的整数)组成,相邻属性用1个空格隔开。
输出格式:
在N行中输出按要求排序后的结果,即:当C=1时,按学号递增排序;当C=2时,按姓名的非递减字典序排序;当C=3时,按成绩的非递减排序。当若干学生具有相同姓名或者相同成绩时,则按他们的学号递增排序。
输入样例:
3 1
000007 James 85
000010 Amy 90
000001 Zoe 60
输出样例:
000001 Zoe 60
000007 James 85
000010 Amy 90
这道题目属于结构体排序,只要注意排序的方式就行了,排序算法O(n*logn)就行了。
注意这道题目给的递增递减顺序,毕竟这东西一下递增一下递减顺序,很容易把自己搞糊涂。
下面给出代码:
#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct Student{
char name[9];
int ID;
int score;
};
int cmp(struct Student *s1,struct Student *s2,int way);
void QuickSort(struct Student *student,int left,int right,int way);
int main(void)
{
int N,C; //记录条数 排序方式
int i;
fscanf(stdin,"%d %d",&N,&C);
struct Student *student;
student=(struct Student *)malloc(N*sizeof(struct Student));
for(i=0;i<N;i++)
fscanf(stdin,"%d %s %d",&student[i].ID,student[i].name,&student[i].score);
QuickSort(student,0,N-1,C);
for(i=0;i<N;i++)
printf("%06d %s %d\n",student[i].ID,student[i].name,student[i].score);
free(student);
return 0;
}
int cmp(struct Student *s1,struct Student *s2,int way)
{
int result=0;
if(1==way)
result=s2->ID-s1->ID;
else if(2==way)
result=strcmp(s2->name,s1->name);
else
result=s2->score-s1->score;
if(!result)
result=s2->ID-s1->ID;
return result;
}
void QuickSort(struct Student *student,int left,int right,int way)
{
if(left>=right)
return ;
int i,j,mid;
int index;
struct Student temp;
i=left;
j=right;
mid=left+((right-left)>>1);
if(3==way)
index=left;
else{
if(cmp(&student[left],&student[right],way)>0){
if(cmp(&student[left],&student[mid],way)>0){
if(cmp(&student[mid],&student[right],way)>0)
index=mid;
else
index=right;
}
else
index=left;
}
else{
if(cmp(&student[mid],&student[right],way)>0)
index=right;
else{
if(cmp(&student[mid],&student[left],way)>0)
index=mid;
else
index=left;
}
} //三数取中法
}
while(i<j){
while(i<j&&cmp(&student[index],&student[j],way)>0)
j--;
while(i<j&&cmp(&student[index],&student[i],way)<=0)
i++;
if(i<j){
temp=student[i];
student[i]=student[j];
student[j]=temp;
}
}
if(index!=i){
temp=student[index];
student[index]=student[i];
student[i]=temp;
}
QuickSort(student,left,i-1,way);
QuickSort(student,i+1,right,way);
return ;
}
测试结果: