1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include<iostream> #include<string> using namespace std; struct Hero { string name; int age; string sex; };
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) { struct Hero temp = heroArray[j]; heroArray[j] = heroArray[j + 1]; heroArray[j + 1] = temp; } } } }
void printHero(struct Hero heroArray[], int len) { for (int i = 0; i < len; i++) { cout << "姓名: " << heroArray[i].name << "年龄:" << heroArray[i].age << "性别: " << heroArray[i].sex << endl; }
} int main() { struct Hero heroArray[5] = { {"刘备",23,"男"}, {"关羽",22,"男"}, {"张飞",20,"男"}, {"赵云",21,"男"}, {"貂蝉",19,"女"}, }; int len = sizeof(heroArray) / sizeof(heroArray[0]);
bubbleSort(heroArray, len); printHero(heroArray, len); return 0; }
|