冒泡排序.C++

bubble sort. C++

本文关键字:C++ 冒泡排序      更新时间:2023-10-16

我的冒泡排序代码出了什么问题,以及如何在排序后(在行搜索之前)写出它。

我使用了基于书中唯一一个例子的代码。在网上搜索了一些关于如何按年龄对数组列表进行排序的指南,但我找不到(至少,对我来说不是太高级的)。所以我带着另一段可能会让你眼睛流血的代码回来了^^对不起。

#include <iostream>
#include <string>
using namespace std;

class person
{
public:
string name;
int age;
void SetInfo(const string _name, int _age)
{
name = _name;
age = _age;
}
int getAge(){ return age; }
};
int Linearsearch(person* personarray, int key)
{
for (int i = 0; i < 10; i++)
{
if (personarray[i].age == key)
return i;
}
return -1;
}
void bubblesort(person mylist[], int n)
{
for (int i = 1; i<n; i++)
{
for (int j = 0; j<n - 1; j++)
{
if (mylist[j].getAge() > mylist[j + 1].getAge())
{
person temp;
temp = mylist[j];
mylist[j] = mylist[j + 1];
mylist[j + 1] = temp;
}
}
}
}
int main()//start of program
{
person mylist[4];//List of people
mylist[0].SetInfo("Calle", 22);
mylist[1].SetInfo("Björn", 20);
mylist[2].SetInfo("Larry", 60);
mylist[3].SetInfo("Lena", 54);
//calling bubblesort()
bubblesort(mylist, 4);

int index = Linearsearch(mylist, 20);
if (index == -1)
cout << "person not found!";
else
cout << "the person you searched for " << mylist[index].name;
cin.get();
return 0;
system("pause");
}

我已经用//注释了我从代码中得到的错误。

首先,我甚至不知道我这里的气泡排序代码会针对年龄,并按照我希望的方式进行排序。

我已经尝试了没有冒泡排序代码的其余代码,它实际上运行得很好(:D)
关于冒泡排序代码或如何在排序后显示它的任何帮助都将是很好的。请投票否决我的问题,或者告诉我如何改革它,让它不那么烦人,而不仅仅是抱怨。请随时帮我编辑问题中的任何内容(如果可以的话)。

首先,您在main函数中声明了mylist,并试图在不属于person类的bubblesort函数中访问它。另一件事是,在对列表进行排序时,不能比较两个对象。您可以根据年龄成员变量对列表对象列表进行排序。在person类中添加getAge()方法。

class person
{
public:
string name;
int age; 
void SetInfo(const string _name, int _age)
{
name = _name;
age = _age;
}
int getAge(){return age;}
};
void bubblesort(person mylist[],int n)
{
for (int i = 1; i<n; i++)
{
for (int j = 0; j<n - 1; j++) //n is "undefined" should n be the number of objects in the list maybe?
{
if (mylist[j].getAge() > mylist[j + 1].getAge()) //the first mylist is "undefined".
{
person temp;
temp = mylist[j];
mylist[j] = mylist[j + 1];
mylist[j + 1] = temp;
}
}
}
}
int main()//start of program
{
person mylist[4];//List of people
mylist[0].SetInfo("Calle", 22);
mylist[1].SetInfo("Björn", 20);
mylist[2].SetInfo("Larry", 60);
mylist[3].SetInfo("Lena", 54);
//calling bubblesort()
bubblesort(mylist,4);
//list.display(); //list is undefined.
int index = Linesearch(mylist, 20);
if (index == -1)
cout << "person not found!";
else
cout << "the person you searched for " << mylist[index].name;
cin.get();
return 0;
system("pause");
}

我认为这应该奏效。phewww。。。

更改

for (int j = 0; j<n - 1; j++)

for (int j = 0; j<i - 1; j++)

在您的bubblesort函数中

我只是简单看了一下,但我认为在冒泡排序中使用n之前,您没有声明n。此外,我不认为你在那里做的是泡沫式的。试试这个:

void bubblesort()
{
int k=1;
while (k==1)
{
k=0;
for (i=1;i<=n;i++)
{
if (mylist[i]>=mylist[i-1])
{
temp=mylist[i];
mylist[i]=mylist[i-1];
mylist[i-1]=temp;
k=1;
}
}
}
}

为你的例子修改它,我相信它会起作用:)