【问题标题】:Having error in Quick Sort Program快速排序程序出错
【发布时间】:2017-01-01 04:57:09
【问题描述】:

错误“Pindex”未在此范围内声明。 (第 15 行)
另外,在函数中声明数组有什么区别

int a[]

int a*

并推荐一些资源来解释排序算法。

#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;


}

【问题讨论】:

  • Pindex 仅在if 语句的范围内声明。添加大括号后,这将很清楚:if (start &lt; last) { int Pindex=Partition(a, start, last); }
  • 作为函数参数,int a[]int* a绝对没有区别。您甚至可以以一种方式声明函数,然后以另一种方式定义它。
  • a* 会报错。 *a 是一个指针。 a[10] 是一个数组。
  • @IgorTandetnik 但 Quicksort 的其他两个语句也仅在 (start
  • 嗯,是的。现在你知道大括号 { } 是干什么用的了。

标签: c++ pointers data-structures quicksort


【解决方案1】:

查看提供的源代码后,主要问题出在Partition()函数。 QuickSort() 中的本地 int Pindex 并不比使用递归调用导致 Segmantation Fault 更成问题。

在疑难解答函数int Partition(int a[] ,int start, int last)中,输入参数是startlast,但是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);
    }
}

【讨论】: