我只是更新我的代码它可以工作,但是当我运行它时会出现一些问题。我把一些" cout"调试我的partiton部分,我不知道它总是将0设置为枢轴。(枢轴应该是我输入的最后一个数字)
这是我的代码
int partiton(vector<int> &a, int low, int up)
{
int pivot = a[up];
int i = low-1;
for (int j = low; j < up; j++)
{
if(a[j] <= pivot)
{
i++;
swap(a[i], a[j]);
}
}
swap(a[i+1], a[up]);
cout<<"pivot: ";
cout<<pivot<<" "<<endl;
return i+1;
}
void quickSort(vector<int> &a, int low, int up)
{
if(low < up)
{
int mid = partiton(a, low, up);
//watch out! The mid position is on the palce, so we don't need to consider it again
//That's why below is mid-1, not mid! Otherwise it will occur overflow error!
quickSort(a, low, mid-1);
quickSort(a, mid+1, up);
}
}
void quickSort(vector<int>&, int, int);
int main()
{
vector<int> A;
int numbers;
while(cin>>numbers)
{
A.push_back(numbers);
}
int low = 0;
int up = A.size();
cout<<"No sorted numbers: ";
for(int i; i < up; i++)
{
cout<<A[i]<<" ";
}
cout << endl;
quickSort(A, low, up);
cout<<"Has sorted numbers: ";
for(int i; i < up; i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
}
答案 0 :(得分:2)
问题的解决方案是在int a[]
和vector<int> a
函数的定义中将partition
更改为quickSort
。因此int partiton(vector<int> a, int low, int up)
和void quickSort(vector<int> a, int low, int up)
应该足以用于编译错误代码。
编译器期望使用与函数声明中的类型相同的参数调用函数,或者至少声明的参数类型必须能够自动解析(推导或绑定,换句话说)到相应的参数特定函数调用的类型。编译器无法将vector
绑定到int a[]
类型,因此会出错。