自己敲的代码:
#include <iostream>
using namespace std;
#include <string>
struct hero
{
string name;
int age;
string gender;
};
struct temp
{
string name;
int age;
string gender;
};
void bubbleSort(struct hero hArray[], struct temp t1)
{
for (int i = 4; i >0; i--)
{
for (int j = 0; j < i; j++)
{
if (hArray[j].age > hArray[j + 1].age)
{
t1.name = hArray[j].name;
hArray[j].name = hArray[j + 1].name;
hArray[j + 1].name = t1.name;
t1.age = hArray[j].age;
hArray[j].age = hArray[j + 1].age;
hArray[j + 1].age = t1.age;
t1.gender = hArray[j].gender;
hArray[j].gender = hArray[j + 1].gender;
hArray[j + 1].gender = t1.gender;
}
}
}
}
void printInfo(struct hero hArray[])
{
for (int i = 0; i < 5; i++)
{
cout << hArray[i].name << " " << hArray[i].age << " " << hArray[i].gender << endl;
}
}
int main()
{
struct hero hArray[5] =
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
};
struct temp t1;
bubbleSort(hArray, t1);
printInfo(hArray);
return 0;
}
优化:
if (hArray[j].age > hArray[j + 1].age)
{
struct hero temp=heroArray[j];
heroArray[j]=heroArray[j+1];
heroArray[j+1]=temp;
}
1、直接在结构体hero
中分配一个临时的结构体变量temp
,不需要定义新的结构体。
2、结构体数组可以整体赋值,不需要一个一个元素进行赋值。