您的位置:首页 > 编程语言 > C语言/C++

C语言数组排序

2020-02-02 07:30 351 查看

有些时候要用char型的数组来储存学号、证件号,这时候的排序就不能简单的用比较大小的方式来完成了。
可以使用C语言头文件#include<string.h>的库函数: strcmp(str_1,str_2)来完成
在结构体里重载了运算符>
下面是strcmp的简单使用及冒泡排序

typedef struct Student {
char id_number[11] = { '\0' };
char name[7] = { '\0' };
char m_grade[4] = { '\0' };
char e_grade[4] = { '\0' };
int operator>(Student& other) {
char* id_1, *id_2;
id_1 = id_number;
id_2 = other.id_number;
if (strcmp(id_1,id_2)>0) {
return 1;
}
else {
return 0;
}
}
}Stu;

void swap(Stu& other, Stu& another) {
Stu temp;
temp = other;
other = another;
another = temp;
}
void bubble_sort(Stu *students,int &length) {
int i, j;
if (length > 1) {
for (i = 0; i < length; i++) {
for (j = i + 1; j < length; j++) {
if ((students[i] > students[j]) == 1) {
swap(students[i], students[j]);
}
}
}
}
}
  • 点赞 2
  • 收藏
  • 分享
  • 文章举报
某科学的烫烫烫 发布了21 篇原创文章 · 获赞 43 · 访问量 3297 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐