冒泡排序与结构体数组的结合
#include<iostream>
using namespace std;
struct hero
{
string name;
int age;
string gender;
};
struct hero heroArray[5]
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"}
};
void bubbleSort(hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len - i - 1; j++)
{
if (heroArray[j].age > heroArray[j + 1].age)
{
struct hero temp = heroArray[j];
heroArray[j] = heroArray[j + 1];
heroArray[j + 1] = temp;
/*int temp1 = heroArray[j].age;
heroArray[j].age = heroArray[j + 1].age;
heroArray[j + 1].age = temp1;
string temp2 = heroArray[j].name;
heroArray[j].name = heroArray[j + 1].name;
heroArray[j + 1].name = temp2;
string temp3 = heroArray[j].gender;
heroArray[j].gender = heroArray[j + 1].gender;
heroArray[j + 1].gender = temp3;*/
}
}
}
}
void printinfo(hero heroArray[], int len)
{
for (int i = 0; i < len; i++)
{
cout << "\t" << heroArray[i].name << " "
<< heroArray[i].age << " "
<< heroArray[i].gender << " "
<< endl;
}
}
int main()
{
int len = sizeof(heroArray) / sizeof(heroArray[0]);
cout << "排序前输出:" << endl;
printinfo(heroArray, len);
cout << endl;
bubbleSort(heroArray, len);
cout << "排序后输出:" << endl;
printinfo(heroArray, len);
system("pause");
return 0;
}