(C++)按照英雄年龄从小到大进行排序(结构体、冒泡排序)

按照英雄的年龄从小到大进行排序
(冒泡排序、结构体)

#include
using namespace std;
#include

struct Hero
{
	string name;
	int age;
	string sex;
};
//1.设计英雄结构体
struct Hero heroArray[5] = {
	{ "刘备",23,"男" },
	{ "关羽",22,"男" },
	{ "张飞",20,"男" },
	{ "赵云",21,"男" },
	{ "貂蝉",19,"女" }
};
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)
{
	cout << "排序后输出" << endl;
	for (int i = 0; i < len; i++)
	{
		cout << "姓名:" << heroArray[i].name << "年龄:"
			<< heroArray[i].age << "性别:"
			<< heroArray[i].sex << endl;
	}
}
int main()
{

	//2.创建数组存放五名英雄
	
	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;
		}
	//3.对数组进行排序,按年龄进行升序排序
	bubbleSort(heroArray, len);
	//4.将排序后结果打印输出
	printHero(heroArray, len);


	system("pause");
 }

运行结果:
(C++)按照英雄年龄从小到大进行排序(结构体、冒泡排序)_第1张图片

你可能感兴趣的:((C++)按照英雄年龄从小到大进行排序(结构体、冒泡排序))