设计一个英雄结构体,包括成员姓名,年龄,性别;通过冒泡排序的算法将英雄按照年龄的大小按照升序排序,最终打印排序后的结果。
#include <iostream>
#include <string>
using namespace std;
struct hero {
string name;
int age;
string sex;
};
void bubblesort(hero array[], int len)
{
for (int i = 0; i < len-1; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (array[j].age > array[j + 1].age)
{
hero temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
void printhero(hero array[], int len)
{
for (int i = 0; i < 5; i++)
{
cout << "\t姓名:" << array[i].name << " 年龄:" << array[i].age <<
" 性别:" << array[i].sex << endl;
}
}
int main()
{
hero array[5] = {
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
int len = sizeof(array) / sizeof(array[0]);
cout << "排序前" << endl;
printhero(array, len);
bubblesort(array, len);
cout << "排序后" << endl;
printhero(array, len);
system("pause");
return 0;
}
