简体   繁体   English

C ++中的冒泡排序算法问题

[英]Bubble sort algorithm issue in C++

My math assignment requires me to develop a few forms of sorting algorithms, and I decided to start off with an "easy" one: the bubble sort. 我的数学作业要求我开发一些形式的排序算法,我决定从一个“简单的”开始:冒泡排序。

I have two lists: 我有两个清单:

3.3 5 9.89 -6

and

-564 1340 42 129 858 1491 1508 246 -1281 655 1506 306 290 -768 116 765 -48 -512 2598 42 2339

I'm able to sort the first one easily, but have an issue mid-sorting for the second one. 我能够轻松地对第一个进行排序,但是对于第二个进行中间排序存在问题。

Here is my small chunk of code that takes care of the sorting. 这是我的一小部分代码,负责排序。

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;
}

Here is the outputed list I get, as you can see it stops being sorted mid way: 这是我得到的输出列表,因为你可以看到它停止在中途排序:

-1281 -564 42 129 246 858 1340 1491 655 1508 1506 306 290 -768 116 765 -48 -512 2598 42 2339

Where did I go wrong in my algorithm? 我的算法在哪里出错了?

This is the working code for bubble sort you might be looking. 这是您可能正在寻找的冒泡排序的工作代码。

  1. First you have to pass the list by ref not value 首先,你必须通过ref not value来传递列表
  2. Bubble up the maximum value at the end of the list. 冒泡列表末尾的最大值。
  3. Properly initialize the it,it2 inside first for loop. 正确初始化它,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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM