在C++中对向量进行排序并打印输出

3

我试图对一个随机生成的int向量进行排序,并在排序完成后打印它。然而,当它被打印出来时,它与原始未排序的向量相同。这是因为我的砖排序算法不正确还是因为我的打印向量的方法有误?任何建议都将不胜感激。

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int brickCount = 0;

void bricksort(vector <int> a)
{
    bool sorted = false;
    while( sorted != true )
    {
        sorted = true;
        for( int i = 1; i < a.size( ) - 1; i += 2 )
        {
            if( a[i] > a[i + 1] ) 
            {
                swap( a[i], a[i + 1] );
                brickCount++;
                sorted = false;
            }
        }
        for( int i = 0; i < a.size() - 1; i += 2 )
        {
            if( a[i] > a[i + 1] )
            {
                swap( a[i], a[i + 1] );
                brickCount++;
                sorted = false;
            }
        }
    }
}

int main()
{
    vector<int>::iterator pos;
    vector <int> nums = {9,8,5,6,76,3,84,234,1,4,6,4,345,54,23,76,85,83,82,61};
    //vector <int> nnums = bricksort(nums);
    bricksort(nums);
    for (pos=nums.begin(); pos!=nums.end(); ++pos) 
    {
        cout << *pos << ' ';
    }
    cout << endl << "brickCount is: " << brickCount << endl;
}

你确定要编写自己的排序算法吗?std::sort 既高效又正确: std::sort(a.begin(), a.end()); - Richard Hodges
2个回答

6
你正在将向量的副本传递给 bricksort 函数。尝试将函数签名更改为: void bricksort(vector <int> &a) 以传递一个引用。

搞定了。谢谢! - Pseudo Sudo

3
尝试将vector<int>的引用传递给函数而非其本身:

void bricksort(vector<int>&a)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接