08-2 结构体练习2
设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。
通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。
五名英雄信息如下:
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",28,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
#include <iostream>
#include <string>
using namespace std;
struct hero
{
string name;
int age;
string sex;
};
int main()
{
struct hero arr[] = { {"刘备",23,"男"},{"关羽",22,"男"},{"张飞",28,"男"},{"赵云",21,"男"},{"貂蝉",19,"女"} };
int len = sizeof(arr) / sizeof(arr[0]);
for (int i = 0;i < len;i++)
{
for (int j = 0;j < (len - i - 1);j++)
{
if (arr[j].age < arr[j + 1].age)
{
struct hero temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
cout << "name\tage\tsex" << endl;
for (int i = 0;i < len;i++)
{
cout << arr[i].name << "\t" << arr[i].age << "\t" << arr[i].sex << endl;
}
system("pause");
return 0;
}
温馨提醒:一不小心写成降序了.......
但是改一下就可以了
if (arr[j].age > arr[j + 1].age)
:-)