请问我写的这个冒泡排序,他怎么不排呢?明明跟着视频走的,人家输出没事,但我有事,我找不到哪错了。
#include <iostream>
#include <string>
using namespace std;
//1.英雄的结构体 姓名年龄 性别
struct hero
{
string name;
int age;
string sex;
};
//冒泡排序
void bubble(struct hero heroarr[],int len)
{
for(int i=0;i<len-1;i++)
{
for(int j=0;j<len-i-1;j++)
{
//如果j下标元素的年龄大于j+1下标元素的年龄,交换
if(heroarr[j].age>heroarr[j+i].age)
{
struct hero temp=heroarr[j];
heroarr[j]=heroarr[j+1];
heroarr[j+1]=temp;
}
}
}
}
//打印
void printhero(struct hero heroarr[],int len)
{
for(int i=0;i<len;i++)
{
cout<<"姓名 "<<heroarr[i].name<<" 年龄 "<<heroarr[i].age
<<" 性别 "<<heroarr[i].sex<<endl;;
}
}
int main()
{
//2.数组反复无名英雄
struct hero heroarr[5]=
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
};
int len=sizeof(heroarr)/sizeof(heroarr[0]);
cout<<"before"<<endl;
for(int i=0;i<len;i++)
{
cout<<"姓名 "<<heroarr[i].name<<" 年龄 "<<heroarr[i].age
<<" 性别 "<<heroarr[i].sex<<endl;;
}
// 3.泡泡 年龄升序
cout<<"after"<<endl;
bubble(heroarr,len);
// 4.将排序后的打印输出
printhero(heroarr,len);
return 0;
}