案例描述:
设计一个(英雄的)结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名结构体成员。通过冒泡排序的算法,将数组中的成员按照年龄进行升序排序,最后打印最终结果。
代码实现:
#include<iostream>
#include<string>
using namespace std;
//1、英雄的结构体
struct hero {
string name;//姓名
int age;//年龄
string hex;//性别
};
//冒泡排序升序
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)
{
int temp = 0;
temp = heroarray[j].age;
heroarray[j].age = heroarray[j + 1].age;
heroarray[j + 1].age= temp;
}
}
}
}
//打印排序后的数组信息
void printinfo(struct hero heroarray[],int len)
{
for (int i = 0; i < len; i++)
{
cout << "姓名: " << heroarray[i].name << " 性别:" << heroarray[i].hex << " 年龄:" << heroarray[i].age << endl;
}
}
int main() {
//2、创建一个数组,存放五名英雄
struct hero heroarray[5]{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"赵云",20,"男"},
{"张飞",21,"男"},
{"貂蝉",19,"女"},
};
int len = sizeof(heroarray) / sizeof(heroarray[0]);
//3、对数组进行排序,按照年龄进行升序排列
bubblesort(heroarray, len);
//4、将排序后的结果打印输出
printinfo(heroarray, len);
system("pause");
return 0;
}
冒泡排序代码实现
数组结构体实现