注册 登录
编程论坛 VC++/MFC

关于快速排序的问题,求解

zhangjian93 发布于 2012-06-07 21:43, 798 次点击
#include<iostream.h>
#define elemtype int
const int  N=10;
void quicksort(elemtype R[],int left,int right)
{
    int i=left,j=right;
    elemtype temp=R[i];
    while(i<j)
    {
        while((R[j]<=temp)&&(j>i))
            j=j-1;
        if(j>i)
        {
            R[i]=R[j];
            i++;
        }
        while ((R[i]<=temp)&&(j>i))
            i++;
        if(i<j)
        {
            R[j]=R[i];
            j--;
        }
    }
    R[i]=temp;
    if(left<i-1)
        quicksort(R,left,j-1);
    if(i+1<right)
        quicksort(R,i+1,right);
}
void main()
{
    int R[N-1];
    cout<<"请输入N个数字:"<<endl;
    for(int i=0;i<N;i++)
    cin>>R[i];
    quicksort(R,0,N-1);
    for(int j=0;j<N;j++)
    cout<<R[j]<<"  ";
    cout<<endl;
}

这是一个快速查找的代码,为什么得不到正确结果????

6 回复
#2
big冰果2012-06-08 17:17
while ((R[i]<=temp)&&(j>i))
            i++;
改成
while ((R[i]>=temp)&&(j>i))//降序
            i++;
你比大小不能两个都大或都小吧
#3
sunnysab2012-06-08 21:38
big冰果回的是真的吗?没学到,不过学习了。
#4
jsjscool2012-06-09 14:36
换一种思路吧。
程序代码:

void quickSort(int a[], int first, int last)
{
    int i = first, j =last;
    int key = a[first];
    int temp = 0;
    if(first<last)
    {
        while(i<j)
        {
            while(i<j&&a[j]>key)
            {
                j--;
            }
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;        
            while(i<j&&a[i]<key)
            {
                i++;
            }
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
        quickSort(a,first,i-1);
        quickSort(a,i+1,last);
    }
}


我现在正在研究几个排序,发现都博大精深!
欢迎到我的博客交流!
http://php.

http://php.
#5
wangyunzhong2012-06-13 23:34
主函数中int R[N-1];改为
int R[N-1];
这样的小问题以后要多注意下哦
#6
hy10802012-06-15 23:29
看VC的源码里边有,偶都是直接复制出来到LINUX下用的
#7
guizhongyun2012-06-16 23:58
cout<<"请输入N个数字:"<<endl;
应该把N改成吧,不然都不知道N是什么
1