#include<iostream>
using namespace std;
#include<string>
struct Hero
{
string Name;
int age;
string sex;
};
struct Hero heroArray[5]={
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",21,"男"},
{"赵云",20,"男"},
{"貂蝉",18,"女"},
};
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+标的元素年龄,就交换两个元素
if(heroArray[j].age>heroArray[j+1].age)
{
struct Hero tempe=heroArray[j];//交换数值
heroArray[j]=heroArray[j+1];
heroArray[j+1]=tempe;
}
}
}
}
//打印函数
void printfHero(struct Hero heroArray[],int len)
{
for(int i=0;i<len;i++)
{
cout<<"英雄的姓名是:"<<heroArray[i].Name<<"年龄为:"<<heroArray[i].age<<"性别为:"
<<heroArray[i].sex<<endl;
}
}
void main()
{
int len=sizeof(heroArray)/sizeof(heroArray[0]);
cout<<"打印前的数组:"<<endl;
for(int i=0;i<len;i++)
{
cout<<"英雄的姓名是:"<<heroArray[i].Name<<"年龄为:"<<heroArray[i].age<<"性别为:"
<<heroArray[i].sex<<endl;
}
//冒泡排序交换数值
bubbleSort(heroArray,len);
printfHero(heroArray,len);
//system("puace");
}
c++结构体冒泡排序
最新推荐文章于 2022-10-17 09:02:53 发布