在快速排序程序中出错
问题描述:
错误在此范围内未声明“Pindex”。 (第15行)
另外,就是与在快速排序程序中出错
int a[]
和
int a*
,并提出一些资源explainatio的排序算法,宣布在功能阵列之间的差异。
#include<iostream>
using namespace std;
int Partition(int a[], int start, int last);
void QuickSort(int a[], int start, int last)
{
/*if(start>=last)
{
return ;
}*/
{ if(start<last)
int Pindex=Partition(a, start, last);
QuickSort(a, start, Pindex-1);
QuickSort(a,Pindex+1, last);
}
}
int Partition(int a[] ,int start, int last)
{
int temp;
int Pindex=start;
int pivot=a[last];
for (int i=0;i<last;i++)
{
if(a[i]<=pivot)
{
temp=a[i];
a[i]=a[Pindex];
a[Pindex]=temp;
Pindex++;
}
}
temp=a[Pindex];
a[Pindex]=a[last];
a[last]=temp;
return Pindex;
}
int main()
{
int n;
cout<<"\n Enter the no of elements ";
cin>>n;
cout<<"\n Enter the elements ";
int A[n];
for (int i=0;i<n;i++)
{
cin>>A[i];
}
QuickSort(A,0,n-1);
cout<<"\n Sorted Array ";
for (int i=0;i<n;i++)
{
cout<<A[i];
}
return 0;
}
答
查看所提供的源代码后,主要问题位于Partition()
函数中。 QuickSort()
中的本地int Pindex
与使用递归调用导致Segmantation Fault不同。
在疑难排解功能
int Partition(int a[] ,int start, int last)
,输入参数是start
和last
,但for循环, 其中Pindex
递增继续for (int i=0;i<last;i++)
并且将导致一个Pindex
大于last
和 最后反转a[Pindex]=a[last];
将导致写入错误。
for循环应在同一范围的输入参数如下进行:
int Partition(int a[] ,int start, int last)
{
int temp;
int Pindex=start;
int pivot=a[last];
// for-loop to the range [start;last[
for (int i=start;i<last;i++)
{
if(a[i]<=pivot)
{
temp=a[i];
a[i]=a[Pindex];
a[Pindex]=temp;
Pindex++;
}
}
temp=a[Pindex];
a[Pindex]=a[last];
a[last]=temp;
return Pindex;
}
然后纠正错字快速排序,当所有工作。
void QuickSort(int a[], int start, int last)
{
/*if(start>=last) // to be deleted
{
return ;
}*/
if(start<last) {
int Pindex=Partition(a, start, last);
QuickSort(a, start, Pindex-1);
QuickSort(a,Pindex+1, last);
}
}
'Pindex'只在'if'语句的范围内声明。一旦你添加了大括号,这将是明确的:'if(start
作为函数参数,'int a []'和'int * a'完全没有区别。你甚至可以用一种方法声明函数,然后用另一种方式定义它。 –
a *会给出错误。 * a是一个指针。一个[10]是一个数组。 – stark