【问题标题】:How to print to the console after every swap using any sorting algorithm?每次交换后如何使用任何排序算法打印到控制台?
【发布时间】:2018-05-13 00:01:59
【问题描述】:

在我的计算机科学入门课程中,我开始学习排序算法的基础知识。到目前为止,我们已经学习了冒泡排序、选择排序和插入排序。

今天下课后,老师要求我们“增强”程序,添加代码以在排序期间每次交换后打印出向量/数组。我完全不知道我将如何做到这一点。我在想这样的事情:

if (swapped) { cout << vec << " "; }

但即使没有尝试,我敢肯定这是行不通的。很感谢任何形式的帮助。到目前为止,这是我的代码:

#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> createVec(int n) {
    unsigned seed = time(0);
    srand(seed);
    vector<int> vec;
    for (int i = 1; i <= n; ++i) {
       vec.push_back(rand() % 100 + 1);
    }
     return vec;
 }

void showVec(vector<int> vec) {
   for (int n : vec) {
      cout << n << " ";
   }
}

void bubbleSort(vector<int> &vec) {
   int n = vec.size();
   bool swapped = true;
   while (swapped) {
      swapped = false;
      for (int i = 1; i <= n-1; ++i) {
          if (vec[i-1] > vec[i]) {
              swap(vec[i-1], vec[i]);
              swapped = true;
          }
      }
   }
}    

 void selectionSort(vector<int> &vec) {
   int n = vec.size();
   int maxIndex;
   for (int i = 0; i <= n-2; ++i) {
     maxIndex = i;
     for (int j = i+1; j <= n-1; ++j) {
      if (vec[j] < vec[maxIndex]) {
           maxIndex = j;
          }
      }
      swap(vec[i], vec[maxIndex]);
   }
}

int main()
{
    vector<int> numbers = createVec(20);
    showVec(numbers);
    cout << endl;
    //bubbleSort(numbers);
    selectionSort(numbers);
    showVec(numbers);
    return 0;
}

【问题讨论】:

  • 在每次调用swap 后添加对showVec 的调用? (这几乎就是增强的描述所说的......)
  • “交换后”的意思正是它所说的。找到执行交换的代码部分,然后立即插入打印代码。

标签: c++ algorithm sorting


【解决方案1】:

例如在被调用函数selectionSort中替换这个语句

swap(vec[i], vec[maxIndex]);

对于下面的陈述

if ( i != maxIndex )
{
    swap(vec[i], vec[maxIndex]);
    showVec( vec );
    cout << endl;
}        

另外,函数showVec 应该将参数声明为具有常量引用类型

void showVec( const vector<int> &vec) {
   for (int n : vec) {
      cout << n << " ";
   }

}

【讨论】:

  • 有趣的是,一旦你看到了解决方案,你总是会意识到它是多么简单和容易,哈哈,谢谢!
猜你喜欢
  • 2014-08-24
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多