【发布时间】:2015-09-06 21:59:08
【问题描述】:
我使用 g++ -std=c++11 Sort.cpp 来编译我的文件。
我的问题是冒泡排序不排序。
也许我正在按值传递向量,但我不知道我是否是第一次尝试使用 c++,所以我选择了使用向量库。
我的代码是:
#include <iostream>
#include <vector>
using namespace std;
void bubbleSort(vector<int> a);
void printVector(vector<int> a);
int main(int argc, char const *argv[])
{
vector<int> a{3,2,6,1};
printVector(a);
bubbleSort(a);
printVector(a);
}
void bubbleSort(vector<int> a)
{
bool swapp = true;
while(swapp)
{
swapp = false;
for (int i = 0; i < a.size()-1; i++)
{
if (a[i]>a[i+1] )
{
a[i] += a[i+1];
a[i+1] = a[i] - a[i+1];
a[i] -=a[i+1];
swapp = true;
}
}
}
}
void printVector(vector<int> a)
{
for (int i=0; i <a.size(); i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
}
我主要声明了一个 int 的向量类型并将列表设为 {3,2,6,1}
然后调用函数printVector,它假装在控制台上打印所有向量的数字并调用bubbleSort函数,最后再次打印。
【问题讨论】:
-
通过引用传递向量:
void bubbleSort(vector<int>& a) -
旁白:如今,聪明的交换技巧弊大于利。
标签: c++ c++11 vector bubble-sort