Skip to content

Instantly share code, notes, and snippets.

@iissnan
Forked from novnan/gist:8395486
Last active January 3, 2016 02:29
Show Gist options
  • Save iissnan/8396337 to your computer and use it in GitHub Desktop.
Save iissnan/8396337 to your computer and use it in GitHub Desktop.
// 有近百名学生选修了某们课程,他们来源不同的专业班级,按班级,学号顺序打印学生的班级名称,学号和姓名。
#include <stdio.h>
#include <string.h>
#define N 5
#define LENGTH 10
char sName[N][LENGTH], sID[N][LENGTH], sClass[N][LENGTH];
void s();
void main()
{
char sTemp;
int i, j;
printf("逐行输入学生的班级,学号和姓名:");
for(i = 0; i < N; i++)
{
scanf("%s%s%s", sClass[i], sID[i], sName[i]);
}
// 冒泡法,排序的依据是班级和学号,即优先排班级,班级一样再按学号排序
for(i = 0; i < N; i++)
{
for(j = i + 1; j < N; j++)
{
if(strcmp(sClass[i], sClass[j]) > 0)
{
// i > j, do not swap.
}
else if(strcmp(sClass[i], sClass[j]) < 0)
{
// i < j, swap class.
s(i, j);
}
else
{
// i = j, compare id.
if(strcmp(sID[i], sID[j]) >= 0) {
// id: i >= j, do not swap.
} else {
// id: i < j, swap.
s(i,j);
}
}
}
}
printf("排序后的班级,学号和姓名:\n");
for(i = 0; i < N; i++)
{
printf("%s %s %s\n", sClass[i], sID[i], sName[i]);
}
}
void s(int i, int j)
{
char sTemp[LENGTH];
strcpy(sTemp, sClass[i]);
strcpy(sClass[i], sClass[j]);
strcpy(sClass[j], sTemp);
strcpy(sTemp, sID[i]);
strcpy(sID[i], sID[j]);
strcpy(sID[j], sTemp);
strcpy(sTemp, sName[i]);
strcpy(sName[i], sName[j]);
strcpy(sName[j], sTemp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment