理解并实现冒泡排序算法,加强写方法的好习惯,理解结构体数组及地址传递
案例描述:设计一个英雄的结构体,包括成员姓名,年龄,性别;创建结构体数组,数组中存放5名英雄。
通过冒泡排序的算法,将数组中的英雄按照年龄进行升序排序,最终打印排序后的结果。
五名英雄信息如下:
{“刘备”,23,“男”},
{“关羽”,22,“男”},
{“张飞”,20,“男”},
{“赵云”,21,“男”},
{“貂蝉”,19,“女”},
#include运行结果:#include using namespace std; struct hero { string name; int age; string sex; }; void allocateSpace(hero heroarr[], int heroarrlength) { string heroname[] = { "刘备","关羽","张飞","赵云","貂蝉" }; int heroage[] = { 23,22,20,21,19 }; string herosex[] = { "男","男","男","男","女" }; for (int i = 0; i < heroarrlength; i++) { heroarr[i].name = heroname[i]; heroarr[i].age = heroage[i]; heroarr[i].sex = herosex[i]; } } void BubbleSort(hero heroarr[], int heroarrlength) { for (int i = 0; i < heroarrlength - 1; i++) { for (int j = 0; j < heroarrlength - 1 - i; j++) { if (heroarr[j].age > heroarr[j + 1].age) { struct hero temp1 = heroarr[j]; heroarr[j] = heroarr[j + 1]; heroarr[j + 1] = temp1; } } } } void printdate(hero heroarr[], int heroarrlength) { cout << "按年龄冒泡排升序后,输出如下:" << endl; for (int i = 0; i < heroarrlength; i++) { cout << "英雄名字:" << heroarr[i].name << " " << "英雄年龄:" << heroarr[i].age << " " << "英雄性别:" << heroarr[i].sex << endl; } } int main() { struct hero heroarr[5]; int heroarrlength = sizeof(heroarr) / sizeof(heroarr[0]); allocateSpace(heroarr, heroarrlength); BubbleSort(heroarr, heroarrlength); printdate(heroarr, heroarrlength); system("pause"); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)