C++ C+中的冒泡排序算法问题+;
我的数学作业要求我开发几种排序算法,我决定从一个“简单”的算法开始:冒泡排序 我有两份清单:C++ C+中的冒泡排序算法问题+;,c++,algorithm,sorting,bubble-sort,C++,Algorithm,Sorting,Bubble Sort,我的数学作业要求我开发几种排序算法,我决定从一个“简单”的算法开始:冒泡排序 我有两份清单: 3.3 5 9.89 -6 及 我能够很容易地对第一个进行排序,但是在对第二个进行排序时遇到了一个问题 下面是我负责排序的一小段代码 int bubbleSort(std::list<double> list) { std::list<double>::iterator it; // First iterator i std::list<double&
3.3 5 9.89 -6
及
我能够很容易地对第一个进行排序,但是在对第二个进行排序时遇到了一个问题
下面是我负责排序的一小段代码
int bubbleSort(std::list<double> list)
{
std::list<double>::iterator it; // First iterator i
std::list<double>::iterator it2; // Second iterator i+1
int comp = 0;
it = list.begin();
it2 = list.begin();
it2++;
for (int i = list.size() - 1; i > 0; --i)
{
for (int j = 0; j < i; j++)
{
comp++;
if (*it2 < *it) // If my second item is smaller than my first one, swap them
{
std::swap(*it2, *it);
it = list.begin();
it2 = list.begin();
it2++;
break;
}
it++;
it2++;
}
}
return comp;
}
我的算法哪里出错了?这是您可能正在查找的冒泡排序的工作代码
#include <bits/stdc++.h>
using namespace std;
int bubbleSort(std::list<double> &list) {
std::list<double>::iterator it; // First iterator i
std::list<double>::iterator it2; // Second iterator i+1
int comp = 0;
for (int i = list.size() - 1; i > 0; --i) {
it = list.begin();
it2 = list.begin();
it2++;
for (int j = 0; j < i; j++) {
comp++;
if (*it2 < *it) { // If my second item is smaller than my first one, swap them
std::swap(*it2, *it);
//it = list.begin();
//it2 = list.begin();
//it2++;
//break;
}
it++;
it2++;
}
}
return comp;
}
int main() {
list<double> l;
int n;
cin >> n;
while (n--) {
double tmp;
cin >> tmp;
l.push_back(tmp);
}
bubbleSort(l);
for (list<double>::iterator i = l.begin(); i != l.end(); i++) {
cout << *i << " ";
}
cout << endl;
}
#包括
使用名称空间std;
int bubbleSort(标准::列表和列表){
std::list::iterator it;//第一个迭代器i
std::list::迭代器it2;//第二个迭代器i+1
int comp=0;
对于(int i=list.size()-1;i>0;--i){
it=list.begin();
it2=list.begin();
it2++;
对于(int j=0;j>n;
而(n--){
双tmp;
cin>>tmp;
l、 推回(tmp);
}
泡泡糖(l);
对于(列表::迭代器i=l.begin();i!=l.end();i++){
您可能需要使用continue而不是break;这会更有意义,谢谢,但是排序似乎没有完成,即使他进行了所需数量的比较以进行排序(准确地说是210)。我使用std::swap
进行排序。您也可以通过ref(&)传递std::list list。
-1281 -564 42 129 246 858 1340 1491 655 1508 1506 306 290 -768 116 765 -48 -512 2598 42 2339
#include <bits/stdc++.h>
using namespace std;
int bubbleSort(std::list<double> &list) {
std::list<double>::iterator it; // First iterator i
std::list<double>::iterator it2; // Second iterator i+1
int comp = 0;
for (int i = list.size() - 1; i > 0; --i) {
it = list.begin();
it2 = list.begin();
it2++;
for (int j = 0; j < i; j++) {
comp++;
if (*it2 < *it) { // If my second item is smaller than my first one, swap them
std::swap(*it2, *it);
//it = list.begin();
//it2 = list.begin();
//it2++;
//break;
}
it++;
it2++;
}
}
return comp;
}
int main() {
list<double> l;
int n;
cin >> n;
while (n--) {
double tmp;
cin >> tmp;
l.push_back(tmp);
}
bubbleSort(l);
for (list<double>::iterator i = l.begin(); i != l.end(); i++) {
cout << *i << " ";
}
cout << endl;
}