关于快速排序的问题

helloDesword 2012-10-29 07:46:20
#include<stdio.h>
#include<stdlib.h>

void quick1(int a[],int low,int up)
{
int i,j,temp;
if(low<up)
{
i=low;
j=up;
temp=a[low];
while(i<j)
{
for(;a[j]>temp;j--);
a[i++]=a[j];
for(;a[i]<=temp;i++);
a[j--]=a[i];
printf("i=%d ,j=%d,\n",i,j);
}
a[i]=temp;
quick1(a,low,i-1);
quick1(a,i+1,up);
}

}
void quick2(int a[],int low,int up)
{
int i,j,temp;
if(low<up)
{
i=low;
j=up;
temp=a[low];
while(i!=j)
{
while(i<j&&a[j]>temp)j--;
if(i<j)a[i++]=a[j];
while(i<j&&a[i]<=temp)i++;
if(i<j)a[j--]=a[i];
printf("i=%d ,j=%d,\n",i,j);
}
a[i]=temp;
quick2(a,low,i-1);
quick2(a,i+1,up);
}

}

int main()
{
int a[]={14,32,45,65,12,22};
int i;
quick2(a,0,5);
for(i=0;i<6;i++)printf("%d ",a[i]);
printf("\n");
quick1(a,0,5);
for(i=0;i<6;i++)printf("%d ",a[i]);
system("pause");
return 0;
}

quick1是我自己写的快速排序,为什么会行不通?不知道哪里错了。
quick2是课本上的。。。请大神求教!!!!感激不尽!
...全文
257 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
helloDesword 2012-10-29
  • 打赏
  • 举报
回复
3楼,5楼,合并起来正解。。
7楼也正解!犀利。
helloDesword 2012-10-29
  • 打赏
  • 举报
回复
3楼,5楼你们的方法我都试了还是不行的。额。
smsgreenlife 2012-10-29
  • 打赏
  • 举报
回复
一对比就知道你的错了,而且你的书上的算法也不是很精简,这个是我写的,你可以参考一下。

void qsort_one_fun(int a[], int begin, int end)
{
if (begin<end)
{
int b=begin;
int e=end;
int temp=a[b];

while(b<e)
{
while (b<e && a[e]>=temp)
{
e--;
}
a[b]=a[e];
while (b<e && a[b]<=temp)
{
b++;
}
a[e]=a[b];
}
a[b]=temp;
qsort_one_fun(a, begin, e-1);
qsort_one_fun(a, e+1, end);
}
return;
}
Inhibitory 2012-10-29
  • 打赏
  • 举报
回复
for(;a[j]>=temp;j--); // 再加个等号
a[i]=a[j]; // 去掉++
for(;a[i]<=temp;i++);
a[j]=a[i]; // 去掉--
Inhibitory 2012-10-29
  • 打赏
  • 举报
回复
for(;a[j]>temp;j--);
a[i]=a[j]; // 去掉++
for(;a[i]<=temp;i++);
a[j]=a[i]; // 去掉--
qzpmww 2012-10-29
  • 打赏
  • 举报
回复
#include<stdio.h>
#include<stdlib.h>
/*tannnn*/
void Swap(int &a,int &b)
{
int temp=a;a=b;b=temp;
}


int Partition(int a[],int p,int r)
{
int i=p,j=r+1;
int x=a[p];
while(true)
{
while(a[++i]<x&&i<r);//从左扫到右,找到第一个大于x的
while(a[--j]>x);//从右扫到左,找到第一个小于x的
if(i>=j) break;//判断下标i,j,当i大于或等于j时,循环结束。
Swap(a[i],a[j]);//交换a[i],a[j]
}
a[p]=a[j];
a[j]=x;
return j;
}//此时已a[j]为基点,左边的都小于或等于a[j],右边的都大于或等于。

void QuickSort(int a[],int p,int r)
{
if(p<r){
int q=Partition(a,p,r);//分割点
QuickSort(a,p,q-1);//递归排序
QuickSort(a,q+1,r);
}
}


int main()
{ int a[]={};
int i=0,n;
printf("请输入待排列数组的个数:");
scanf("%d",&n);
printf("请输入待排列数组:");
for(i=0;i<n;i++) scanf("%d",&a[i]);
QuickSort(a,0,n-1);
for(i=0;i<n;i++) printf("%d ",a[i]);
system("pause");
}
自己对比一下吧
exfoided 2012-10-29
  • 打赏
  • 举报
回复
for循环里j和i的值会改变,可能导致i>j的情况
将for(;a[j]>temp;j--);改成for(;a[j]>temp && i<j;j--);
for(;a[i]<=temp;i++);改成 for(;a[i]<=temp && i<j;i++);
看下
AnYidan 2012-10-29
  • 打赏
  • 举报
回复
输入一个几个元素的数组,单步一下
guochanoo7 2012-10-29
  • 打赏
  • 举报
回复
这两个sort程序看着这么像,就改了中间while换成了for,你看看那个地方控制不足就可以了。你可以用debug工具追踪一下各次循环的状态就能看出来那个地方出错误了

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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