请教:我的quicksort哪里出错了?希望大家帮我找找,调试时提示stack overflow!.
void QuickSort(int a[],int m, int n)
{
int i,j,key;
i = m;
j = n;
key = a[i];
int temp;
while(i<=j)
{
while(key>a[++i]);
while(key<a[j--]);
if(i<j)
{
temp= a[i];
a[i]= a[j];
a[j] = temp;
}
else
{
//int temp;
temp = a[j];
a[j] = a[m];
a[m] = temp;
}
QuickSort(a,m,j-1);
QuickSort(a,j,n);
}
}
void main()
{
int b []={4,3,2,1,-1};
int size = sizeof(b)/sizeof(int);
QuickSort(b,0,size-1);//为什么有错误呀??
for(int i= 0;i<5;i++)
cout<<b[i]<<endl;
}
[解决办法]
递归没终止条件。
开头加上 if(m>=n)return ;
void QuickSort(int a[],int m, int n){if(m>=n)return ;int i,j,key;i = m;j = n;key = a[i];int temp;while(i<=j){while(key>a[++i]);while(key<a[j--]);if(i<j){temp= a[i];a[i]= a[j];a[j] = temp;}else{//int temp;temp = a[j];a[j] = a[m];a[m] = temp;}QuickSort(a,m,j-1);QuickSort(a,j,n);}
[解决办法]