#include<iostream>
using namespace std;
#include<string>
struct hero
{
string name;
int age;
string sex;
};
void paixu(struct hero a[], int len)//简单的冒泡排序,不懂的可以看我之前写的冒泡排序
{
for (int i = 0;i < len - 1;i++)//对每一对相邻元素做比较的工作,持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较,所以共需(元素-1)次
{
for (int j = 0;j < len - i - 1;j++)//对每一对相邻元素做比较的工作,所以要比较(元素-i)次
{
struct hero b;
if (a[j + 1].age < a[j].age)//比较相邻的元素。如果第一个比第二个大,就交换他们两个
{
b = a[j];
a[j] = a[j + 1];
a[j + 1] = b;
}
}
}
}
int main()
{
struct hero a[5] =
{
{"刘备",23,"男"}, {"关羽",22,"男"} ,{"张飞",20,"男"}, {"赵云",21,"男"} ,{"貂蝉",19,"女"}
};
int len = (sizeof a) / (sizeof a[0]);
paixu(a, len);
for (int i = 0;i < 5;i++)
{
cout << a[i].name << " " << a[i].age << " " << a[i].sex << endl;
}
return 0;
}
代码较为简单,简单参考一下就行。