[英]bubble sort. C++
我的气泡排序代码有什么问题,如何在排序后(在Linesearch之前)将其写出。
我使用的代码基于我在书中可以找到的唯一示例。 在网上搜索了一些有关如何按年龄对阵列列表进行排序的指南,但我找不到一个(至少不是一个对我来说不太高级的列表)。 因此,我又返回了另一段代码,这可能会使您的眼睛流血^^对不起。
#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)。
气泡排序代码或排序后如何显示的任何帮助都很好。 请投票否决我的问题,或者告诉我如何进行修改以减少烦恼,而不仅仅是抱怨。 并随时帮助我编辑问题中的所有内容(如果可以)。
更改
for (int j = 0; j<n - 1; j++)
至
for (int j = 0; j<i - 1; j++)
在你的bubbleort函数中
我只是快速浏览了一下,但我不认为您在将它用于冒泡排序之前先声明了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;
}
}
}
}
修改它为您的示例,我敢肯定它将起作用:)
首先,您已在main函数中声明mylist
,并尝试在不属于person类的bubblesort
函数中bubblesort
进行访问。 另一件事是您无法像对列表进行排序那样比较两个对象。 您可以根据年龄成员变量对mylist对象列表进行排序。 在人员类中添加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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.