冒泡排序與結構體陣列的結合
#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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/301696.html
標籤:其他
