/*案例说明
设计一个英雄的数组,包括成员姓名,年龄,性别,创建结构体数组,数组中存放五名英雄。通过冒泡排序的算法,将数组中的英熊按照
年龄进行升序排列,最终打印排序后的结果
*/
#include<iostream>
using namespace std;
#include<string>;
//声明一个hero的结构体数组
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++) {
//如果j下标下的年龄大于j+1下标下的年龄,交换两个元素
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].name << "年龄 " << heroArray[i].age << "性别 " << heroArray[i].sex << endl;
}
}
int main()
{
struct Hero heroArray[] = {
{"刘备",23,"男"},
{"张飞",24,"男"},
{"貂蝉",20,"女"},
{"赵云",25,"男"},
{"吕布",21,"男"},
};
int len = sizeof(heroArray) / sizeof(heroArray[0]);
/*for (int i = 0; i < len; i++) {
cout << "姓名: " << heroArray[i].name << "年龄 "<<heroArray[i].age<<"性别 "<<heroArray[i].sex<<endl;
};*/
//对数组进行排序,按照年龄进行升序排序
bubbleSort(heroArray, len);
printHero(heroArray,len);
system("pause");
return 0;
}