在快速排序程序中有错误
Having error in Quick Sort Program
错误" 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)
中,输入参数为start
和last
,但是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);
}
}
相关文章:
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 我的代码中有错误,未声明的标识符
- C++ LeetCode #377 的 DP 解决方案中,此代码是否有错误?
- 试图建立银行管理系统,但有错误
- 我试图创建临时对象的方式有错误吗
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- 我在OpenCV中有错误的"approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, true)"
- 我在这个 C++ 代码上有错误吗?
- 是视觉C++优化器错误还是我的代码中有错误?
- 为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
- 对此有错误
- C :数据文件有错误:预期的无限制ID
- 一个带有参数的程序,为什么此程序有错误的答案
- 仅使用boost.datetime在Windows上有错误
- 使用向量循环时,是否有错误
- 在快速排序程序中有错误
- 有错误的程序仍在编译吗
- Dyanamic 数组类,程序运行良好,但有错误
- 为什么nasm说我在g++创建的程序集中有错误
- 一种程序,用于纠正运算符中有错误的C++程序