使用类在 C++ 中快速排序错误
quick sort error in c++ using classes
我在C++年做了一个程序,使用类和对象进行快速排序。我已经在在线编译器上编译了它,发现它超时了,因为这段代码占用了太多的时间和内存。
当我后来在Visual C++ 2010上编译它时,它说unhandled exception : stack overflow
我试图找出在类成员函数void quick sort (a[],l,r)
上运行的无限循环。请帮忙。
#include <iostream>
using namespace std;
class sort;
int main()
{
class sort
{
public:
int split(int a[],int l,int r)
{
int i,j,p,t;
p=a[l];
i=(l+1);
j=r;
while (l<=r)
{
while ((a[i]<p)&&(i<j))
r--;
while ((a[j]>p)&&(l<r))
l++;
if (i<=j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
t=p;
p=a[j];
a[j]=p;
return j;
}
void quicksort(int a[],int l,int r)
{
int s;
if (l<r)
{
s=split(a,l,r);
quicksort(a,l,(s-1));
quicksort(a,(s+1),l);
}
}
} obj1;
int a[30],n,i;
cout<<"nEnter no of elements :t 5";
n=5;
cout<<"nEnter elements :n";
a[0]=9;
a[1]=6;
a[2]=3;
a[3]=5;
a[4]=1;
cout<<"nElemets before sort :n";
for(i=0;i<n;i++)
cout<<" "<<a[i];
obj1.quicksort(a,0,(n-1));
cout<<"nElements after sort:n";
for (i=0;i<n;i++)
cout<<" "<<a[i];
return 0;
}
这里有几个问题:
int split(int a[],int l,int r)
{
int i,j,p,t;
p=a[l];
i=(l+1);
j=r;
// consider what will happen for an array with just 1 or 2 elements?
while (l<=r) // should be while i<=j;
{
while ((a[i]<p)&&(i<j))
r--; //should be j--
while ((a[j]>p)&&(l<r))
l++; // should be i++
if (i<=j) // sadly this will only true when you've got an array with 1 element
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
t=p;
p=a[j];
a[j]=p;
return j;
}
关键问题是这里的快速排序算法不正确。 它的工作原理如下:
0. make i = l+1 and j = r;
1. while true:
1.1 while a[i]<a[l] i++
1.2 while a[j]>a[l] j--
1.3 break if i>= j;
1.4 exchange a[i] and a[j]
2. exchange a[l] and a[j]
你在实现中做不同的事情。
相关文章:
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 并行快速排序分区中的隔离错误
- 快速排序;分段错误,但找不到位置?
- 在最坏的情况下试验快速排序.它运行良好,但在最坏的情况下发生未知错误.我想
- C++ 快速排序错误
- 快速排序中的交换函数给出错误的输出
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 在快速排序程序中有错误
- 为什么我在快速排序时遇到分段错误
- C++:在模板快速排序功能中接收"couldn't deduce template parameter"错误
- 快速排序不起作用(分段错误)
- 使用C++的快速排序错误
- 错误的线程访问/seg故障快速排序
- 分区出现快速排序逻辑错误
- c++快速排序算法中500000排序整数数组的Seg错误
- 使用类在 C++ 中快速排序错误
- 递归快速排序导致分段错误(不是溢出)
- 快速排序错误:变量周围的堆栈已损坏
- 快速排序错误,可能是1个c++错误