请高手帮我看看这个快排哪里出错了?

LAST_MAN 2012-06-11 03:20:18
#include<iostream>
using namespace std;
int Partition(int a[],int low,int high){
int pivot=a[low];//第0个位置记录枢轴值
while (low < high)
{
while (low<high && pivot<a[high])
{
--high; //将比枢轴小的记录移到低端
}
a[low]=a[high];
low++;
while (low<high &&pivot>a[low])
{
low++;
}
a[high]=a[low];
high--;
}


if(low>=high)
{
a[low]=pivot;

cout<<"返回的low值是"<<low<<endl;
for(int i=0;i<low;i++){
cout<<a[i]<<" ";}
cout<<'\n';

return low;
}
else
{
a[high]=pivot;
cout<<high<<endl;;
return high;
}

}
void QuickSort(int a[],int low,int high)
{
int pivotLocation;//记录枢轴位置
if (low<high)//保证区间长度大于1
{
pivotLocation=Partition(a,low,high);//划分区间,并得到枢轴位置
QuickSort(a,low,pivotLocation-1);//对枢轴左区间进行快排
QuickSort(a,pivotLocation+1,high);//对枢轴右区间进行快排
}
}
int main()
{
int b[10]={6,7,4,1,52,33,2,1,4,1};

Partition(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
cout<<endl;

QuickSort(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}

return 0;
}


不知道哪一步出错了,求解答
...全文
66 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
W170532934 2012-06-11
  • 打赏
  • 举报
回复
楼上正解啊
LAST_MAN 2012-06-11
  • 打赏
  • 举报
回复
@tongzhipeng5699
你修改了之后是可以的
LAST_MAN 2012-06-11
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]
另外if(low>=high)判断是多余的
因为了while循环的时候一定是low=high ,直接 return low或者return high都行。
[/Quote]
我用断点调试,出现了high=5
low=6...
不知道为什么
后来只能加上这个,才能分区正确,但是执行QuickSort()就出错了
tongzhipeng5699 2012-06-11
  • 打赏
  • 举报
回复
另外if(low>=high)判断是多余的
因为了while循环的时候一定是low=high ,直接 return low或者return high都行。
tongzhipeng5699 2012-06-11
  • 打赏
  • 举报
回复
高位与低位交换时,需要加if(low<high) 判断

#include<iostream>
using namespace std;
int Partition(int a[],int low,int high){
int pivot=a[low];//第0个位置记录枢轴值
while (low < high)
{
while (low<high && pivot<a[high])
{
--high; //将比枢轴小的记录移到低端
}
if(low<high) a[low++]=a[high];//这里要加 low<high条件 因为可能有low==high的情况出现

while (low<high &&pivot>=a[low])
{
low++;
}
if(low<high) a[high--]=a[low];

}


if(low>=high)
{
a[low]=pivot;

// cout<<"返回的low值是"<<low<<endl;
// for(int i=0;i<low;i++){
// cout<<a[i]<<" ";}
// cout<<'\n';

return low;
}
else
{
a[high]=pivot;
// cout<<high<<endl;;
return high;
}

}
void QuickSort(int a[],int low,int high)
{
int pivotLocation;//记录枢轴位置
if (low<high)//保证区间长度大于1
{
pivotLocation=Partition(a,low,high);//划分区间,并得到枢轴位置
QuickSort(a,low,pivotLocation-1);//对枢轴左区间进行快排
QuickSort(a,pivotLocation+1,high);//对枢轴右区间进行快排
}
}
int main()
{
int b[10]={6,7,4,1,52,33,2,1,4,1};

Partition(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}
cout<<endl;

QuickSort(b,0,9);
for(int i=0;i<10;i++){
cout<<b[i]<<" ";
}

return 0;
}

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧