Sorting 为什么我的快速排序实现不起作用?
这是我的密码:Sorting 为什么我的快速排序实现不起作用?,sorting,scope,implementation,quicksort,Sorting,Scope,Implementation,Quicksort,这是我的密码: #include<iostream> using namespace std; //Array that needs to be sorted int a[]={234,45,234,65,234,65,234,567,234,123,11,23,43,45,6,7,7,4,233,4,6,4,3,11,23,556,7,1,2,3,4,5,6,7,}; //Calculate the size of the array int n=sizeof(a)/sizeo
#include<iostream>
using namespace std;
//Array that needs to be sorted
int a[]={234,45,234,65,234,65,234,567,234,123,11,23,43,45,6,7,7,4,233,4,6,4,3,11,23,556,7,1,2,3,4,5,6,7,};
//Calculate the size of the array
int n=sizeof(a)/sizeof(a[0]);
//Swap utility function to swap two numbers
void swap(int a,int b)
{
int t=a;
a=b;
b=t;
}
//Partion the array into two according to the pivot,i.e a[r]
int partion(int p,int r)
{
int x=a[r],i=p-1;
for(int j=p;j<r;j++)
if(a[j]<=x)
{
i++;
swap(a[i],a[j]);
}
swap(a[r],a[i+1]);
return i+1;
}
//Recursive method to sort the array
void quick_sort(int p,int r)
{
if(p<r)
{
int q=partion(p,r);
quick_sort(p,q-1);
quick_sort(q+1,r);
}
}
int main()
{
cout<<"\nOriginal array:\n";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
quick_sort(0,n-1);
cout<<"Sorted array:\n";
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
我不确定是什么问题。这是一个快速排序实现错误还是数组“a[]”范围内的错误或其他错误
数组“a[]”是一个全局变量,因此我假定分区和快速排序对其进行操作。阵列似乎保持不变。看看您的交换功能:
void swap(int a,int b)
{
int t=a;
a=b;
b=t;
}
它正在更改复制的变量的值。您希望通过引用传入a和b,以便更改它们的值
void swap(int &a,int &b)
{
int t=a;
a=b;
b=t;
}
void swap(int &a,int &b)
{
int t=a;
a=b;
b=t;
}