请问我写的这个冒泡排序,他怎么不排呢?明明跟着视频走的,人家输出没事,但我有事,我找不到哪错了。
#include
#include
using namespace std;
//1.英雄的结构体 姓名年龄 性别
struct hero
{
string name;
int age;
string sex;
};
//冒泡排序
void bubble(struct hero heroarr[],int len)
{
for(int i=0;i-1;i++)
{
for(int j=0;j-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"姓名 "<" 年龄 "<" 性别 "<int main()
{
//2.数组反复无名英雄
struct hero heroarr[5]=
{
{"刘备",23,"男"},
{"关羽",22,"男"},
{"张飞",20,"男"},
{"赵云",21,"男"},
{"貂蝉",19,"女"},
};
int len=sizeof(heroarr)/sizeof(heroarr[0]);
cout<<"before"<for(int i=0;i"姓名 "<" 年龄 "<" 性别 "<// 3.泡泡 年龄升序
cout<<"after"<bubble(heroarr,len);
// 4.将排序后的打印输出
printhero(heroarr,len);
return 0;
}
if(heroarr[j].age>heroarr[j+i].age)
应该是
if(heroarr[j].age>heroarr[j+1].age)
int len=sizeof(heroarr)/sizeof(heroarr[0]);
这是错误的,因为结构中有string类型,不能用sizeof计算长度的
并且19行 if(heroarr[j].age>heroarr[j+i].age)这里也写错了,是heroarr[j+1]