【问题标题】:Bubble sort algorithm issue in C++C++中的冒泡排序算法问题
【发布时间】:2016-09-22 09:12:33
【问题描述】:

我的数学作业要求我开发几种形式的排序算法,我决定从一个“简单”的算法开始:冒泡排序。

我有两个列表:

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

我的算法哪里出错了?

【问题讨论】:

  • 也许你需要使用 continue 而不是 break;
  • 这会更有意义,谢谢,但即使他进行了所需数量的比较以对其进行排序(准确地说是 210),排序似乎也没有完成。跨度>
  • 我正在使用std::swap 进行排序。
  • 你也可以通过 ref (&) 传递 std::list 列表。

标签: c++ algorithm sorting bubble-sort


【解决方案1】:

这是您可能正在寻找的冒泡排序的工作代码。

  1. 首先你必须通过引用而不是值来传递列表
  2. 在列表末尾冒出最大值。
  3. 在第一个for循环中正确初始化it,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;
    }
    

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 2013-07-13
    • 2016-03-19
    • 1970-01-01
    • 2020-12-19
    • 2019-04-18
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多