代码实现:
#include<iostream>
#include<string>
#include<ctime>
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 tmp = heroArray[j];
heroArray[j] = heroArray[j + 1];
heroArray[j + 1] = tmp;
}
}
}
void printInfo(struct Hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
std::cout << " name:" << heroArray[i].name << " age:" << heroArray[i].age << " Sex:" << heroArray[i].sex << endl;
}
}
//结构体做参数
int main()
{
//1、设计英雄结构体
//2、创建数组存放5名英雄
struct Hero heroArray[5] =
{
{ "刘备" ,23,"男"},
{ "关羽" ,22,"男" },
{ "张飞" ,21,"男" },
{ "赵云" ,20,"男" },
{ "貂蝉" ,19,"女" },
};
int len = sizeof(heroArray) / sizeof(heroArray[0]);
//3、对数组尽心排序、按照年龄进行升序排序
BubbleSort(heroArray, len);
//4、打印输出
printInfo(heroArray, len);
system("pause");
return 0;
}
输出结果: