每次交换后,如何使用任何排序算法打印到控制台



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

今天上课后,讲师要求我们"增强"程序,通过添加代码在排序期间进行每个交换后打印出矢量/数组。对于如何实现这一目标,我完全不知所措。我在想:

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

例如在称为函数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 << " ";
   }

}

最新更新