在快速排序程序中有错误

Having error in Quick Sort Program

本文关键字:有错误 程序 快速排序      更新时间:2023-10-16

错误" 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;

}

查看提供的源代码后,主要问题位于Partition()函数中。QuickSort()中的本地int Pindex比使用递归呼叫引起segmantation故障的问题。

在故障排除函数 int Partition(int a[] ,int start, int last)中,输入参数为 startlast,但是for-loop, Pindex的递增继续为 for (int i=0;i<last;i++),并且会导致Pindex大于last,并且 上次反转a[Pindex]=a[last];将导致写入错误。

循环应在输入参数的相同范围内完成:

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

然后,在纠正QuickSort错字时,所有人都在工作。

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);
    }
}