首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

写的快排代码,qsort 函数有点不对头,以 5 4 7 6 3为例,第一次分段后半段进不去,哪里出了有关问题,请指出.已经 搞了好久了,大神帮上小弟我

2013-03-01 
写的快排代码,qsort 函数有点不对头,以 5 4 7 6 3为例,第一次分段后半段进不去,哪里出了问题,请指出.已经

写的快排代码,qsort 函数有点不对头,以 5 4 7 6 3为例,第一次分段后半段进不去,哪里出了问题,请指出.已经 搞了好久了,大神帮下我。
#include <iostream>
#include <iomanip>
using namespace std;
void qsort(int * L,int low ,int high);
int partition(int *L,int low ,int high);
void swap (int * a,int *b);
int main()
{
int i, n,*L;
cout<<"请输入有多少个数进行排序:"<<endl;
cin>>n;
L=new int[n];
cout<<"请输入要排序的这"<<n<<"个数:"<<endl;
for(i=0;i<n;i++)
{
cin>>L[i];
}
cout<<"排序之前:"<<endl;
for(i=0;i<n;i++)
{
cout<<setw(8)<<L[i];
}
qsort(L,0,n-1);
cout<<"排序之后:"<<endl;
for(i=0;i<n;i++)
{
cout<<setw(8)<<L[i];
}
getchar();
return 0;
}
void qsort(int * L,int low,int high)
{
int pivotloc;
cout<<"get in qsort"<<endl;
cout<<"low:"<<low<<endl<<"high:"<<high<<endl;
while(low<high)
{
pivotloc=partition(L,low,high);
cout<<"pivotloc"<<pivotloc<<endl;
cout<<"11111111111111分成"<<low<<" and " <<pivotloc-1<<"段"<<endl;
qsort(L,low,pivotloc-1);
cout<<"22222222222222分成"<<pivotloc+1<<" and " <<high<<"段"<<endl;
qsort(L,pivotloc+1,high);
}
getchar();
}
int partition(int *L,int low1 ,int high1)
{
int pivotkey=L[low1];
cout<<"get in partition"<<endl;
while(low1<high1)
{
while(low1<high1&&L[high1]>=pivotkey)
{
high1--;
}
swap(&L[low1],&L[high1]);
while(low1<high1&&L[low1]<=pivotkey)
{
low1++;
}
swap(&L[low1],&L[high1]);
}
//cout<<"low:"<<low<<endl<<"high:"<<high<<endl;
return low1;
}
void swap (int * a,int *b)
{
int temp;
temp= *a;
*a=*b;
*b=temp;
}
[解决办法]
好象是在qsort里的这一段:
while (low < high)
{
  pivotloc = partition(L, low, high);
  cout << "pivotloc" << pivotloc << endl;
  cout << "11111111111111分成" << low << " and " << pivotloc-1 << "段" << endl;
  qsort(L, low, pivotloc-1);
  cout << "22222222222222分成" << pivotloc+1 << " and " << high << "段" <<endl;
  qsort(L, pivotloc+1, high);
}
你始终没有更改 low 和 high,所以一旦进入循环,是不会结束的
qsort更多的是采用递归来处理。
[解决办法]
这是一段递归的代码,采用了你的变量。
(没经过测试,不过,应该不会有大问题)


void qsort(int* L, int low, int high)
{
  if (low >= high)
  {
    return;
  }
  int pivotloc = partition(L, low, high);
  qsort(L, low, pivotloc-1);
  qsort(L, pivotloc+1, high);
}

[解决办法]
实际应用的qsort,还需要考虑很多问题。比如:是否会在递归过程中产生过多的调用导致堆栈溢出、要怎样提高效率等等。
STL中有sort,效率挺高的,建议用它们来完成排序工作。毕竟,那些代码是很多高手研究出来的。

热点排行