项目要求:将结构体数组中按年龄排序
#include <iostream>
using namespace std;
struct Hero {
string name;
int age;
string sex;
};
void bubbleSort(struct Hero heroArray[], int len) {
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (heroArray[j].age > heroArray[j + 1].age) {
struct Hero temp = heroArray[j];
heroArray[j] = heroArray[j + 1];
heroArray[j + 1] = temp;
}
}
}
}
void printHero(struct Hero heroArray[], int len) {
for (int i = 0; i < len; i++) {
cout << heroArray[i].sex << "性的" << heroArray[i].name << heroArray[i].age << "了" << endl;
}
}
int main() {
struct Hero heroArray[5] = {
{"whh",23,"男"},
{"lll",22,"男"},
{"zsh",21,"男"},
{"zhy",20,"男"},
{"yjh",19,"男"},
};
int len = sizeof(heroArray) / sizeof(heroArray[0]);
//年龄升序
bubbleSort(heroArray, len);
//打印
printHero(heroArray, len);
system("pause");
return 0;
}