C++ C++;:不受Void函数影响的变量
我已经尝试实现了一个基本的快速排序算法,我认为我已经正确地实现了它。但是,这些函数根本不会影响数组。原因可能是什么?我不知道出了什么问题,所以我决定在这里咨询我的程序员同事:C++ C++;:不受Void函数影响的变量,c++,performance,algorithm,sorting,C++,Performance,Algorithm,Sorting,我已经尝试实现了一个基本的快速排序算法,我认为我已经正确地实现了它。但是,这些函数根本不会影响数组。原因可能是什么?我不知道出了什么问题,所以我决定在这里咨询我的程序员同事: #include <iostream> #include <vector> using namespace std; int partition(vector<int> A,int low,int high) { int pivot=A[high-1]; int bo
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int> A,int low,int high)
{
int pivot=A[high-1];
int boundryForLowerArray=low-1;
for(int i=low;i<high-2;i++)
{
if(A[i]<=pivot)
{
boundryForLowerArray++;
swap(A[i],A[boundryForLowerArray]);
}
}
swap(pivot,A[boundryForLowerArray+1]);
return boundryForLowerArray+1;
}
void quickSort(vector<int>A,int low,int high)
{
if(low<high)
{
int q=partition(A,low,high);
quickSort(A, low, q-1);
quickSort(A, q+1, high);
}
}
int main(int argc, const char * argv[])
{
vector<int>A,sorted;
A.push_back(2);
A.push_back(8);
A.push_back(7);
A.push_back(1);
A.push_back(3);
A.push_back(5);
A.push_back(6);
A.push_back(4);
quickSort(A, 0, A.size());
for(int i=0;i<A.size();i++)
cout<<A[i]<<" ";
return 0;
}
#包括
#包括
使用名称空间std;
整型分区(向量A,整型低,整型高)
{
int pivot=A[high-1];
int boundryForLowerArray=low-1;
对于(int i=low;i您是通过值传递而不是通过引用传递,因此快速排序
是复制并排序。请尝试通过引用传递向量:
int partition(vector<int>& A,int low,int high)
int分区(向量&A、int低、int高)
…和
void quickSort(vector<int>& A,int low,int high)
void快速排序(向量&A、整数低位、整数高位)
因为您通过值而不是引用来传递参数。实际上,您应该有一个包含迭代器的函数,用于数组的开头和结尾(vec.begin(),vec.end())作为参数。此外,您的算法应该接受任何类型的迭代器。因此,您应该使用模板
template<class Iterator>
void quick_sort(Iterator begin, Iterator end) {
for(auto iter = begin;iter != end;iter++)
*iter; // access to the value of the iterator
模板
void quick_sort(迭代器开始,迭代器结束){
for(自动iter=begin;iter!=end;iter++)
*iter;//访问迭代器的值
+1作为一个完整的示例程序。@rolandbishop只需将上面提到的两行代码(即vector
更改为vector&
),它就像一个符咒一样工作。我想是的,但是它让我意识到我编写了一个快速排序算法,它不会对lol进行排序。