[英]Bubble sort algorithm issue in C++
我的數學作業要求我開發一些形式的排序算法,我決定從一個“簡單的”開始:冒泡排序。
我有兩個清單:
3.3 5 9.89 -6
和
-564 1340 42 129 858 1491 1508 246 -1281 655 1506 306 290 -768 116 765 -48 -512 2598 42 2339
我能夠輕松地對第一個進行排序,但是對於第二個進行中間排序存在問題。
這是我的一小部分代碼,負責排序。
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;
}
這是我得到的輸出列表,因為你可以看到它停止在中途排序:
-1281 -564 42 129 246 858 1340 1491 655 1508 1506 306 290 -768 116 765 -48 -512 2598 42 2339
我的算法在哪里出錯了?
這是您可能正在尋找的冒泡排序的工作代碼。
正確初始化它,it2在第一個循環中。
#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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.