sort函数用于c,对特定区间的所有元素进行排序。 默认值为升序,但也可以按降序排序。 sort函数的排序时间复杂度为n*log2n,比冒泡等排序算法更高效。 sort函数包含在头文件#include的c标准库中。
主题说明:
有n个学生的数据,把学生数据按成绩从高到低排序,成绩相同则按名字字母顺序排序,名字字母顺序也相同则按学生年龄顺序排序,输出n个学生排序的信息。
#包含
#包含
#包含
用户命名空间STD;
结构e {
char name[101];
int age;
int score;
}buf[1000];
BOOLCMP(ea,E b ) {
if(a.score!=b.score(returna.scoreb.score;
inttmp=strcmp(a.name,b.name );
if(tmp!=0)返回tmp 0;
else return a.age b.age;
}
int main () )。
int n;
while(Scanf_s ) ' %d ',n )!=EOF
for(intI=0; i n; I ) {
scanf_s('%s%d%d ),buf[i].name,sizeof ) buf[i].name ),buf[i].age,buf[i].score );
}
sort(buf,buf n,cmp );
printf((n );
for(intI=0; i n; I ) {
printf(%s%d%dn ),buf[i].name,buf[i].age,buf[i].score );
}
}
返回0;
}
注意事项
区分使用scanf和scanf_s。 scanf_s必须指定缓冲区的大小,因此将参数增加一个。 Unlike scanf and wscanf,scanf _ sandwscanf _ srequireyoutospecifybuffersizesforsomeparameters.specifythesizesforallc,c, specifythesizesforallc or string控制集[ ] parameters.thebuffersizeincharactersispassedasanadditionalparameter.itimmediatelyfollowsthepointertothebufferorvariable.ior if you're reading a string,thebuffersizeforthatstringispassedasfollows 3360
char s[10];
scanf_s('%9s ',s,) ) unsigned ) _countof(s ) ); //buffer size is 10,width specification is 9
结果
通过运算符重载实现
#包含
#包含
#包含
用户命名空间STD;
结构e {
char name[101];
int age;
int score;
bool操作器
if (呼叫!=b.score(returnscoreb.score;
inttmp=strcmp(name,b.name );
if(tmp!=0)返回tmp 0;
else return age b.age;
}
}buf[1000];
int main () )。
int n;
while(Scanf_s ) ' %d ',n )!=EOF
for(intI=0; i n; I ) {
scanf_s('%s%d%d ),buf[i].name,sizeof ) buf[i].name ),buf[i].age,buf[i].score );
}
sort(buf,buf n );
printf((n );
for(intI=0; i n; I ) {
printf(%s%d%dn ),buf[i].name,buf[i].age,buf[i].score );
}
}
返回0;
}
由于结构体的大小运算符已经显示出来,所以计算机知道该结构体的顺序规则。 sort函数只使用更小的算子来决定顺序,小的先。 因此,调用sort时不需要特别指定排序规则。 也就是说,不使用第三个参数。
总结
到目前为止,我介绍了一篇关于c的sort函数对成绩进行排名的文章。 有关c sort函数的内容,请搜索原始脚本家的以前文章或以下相关文章。 希望今后能支持很多脚本家。