快速排序有关问题~(根据算法导论下的伪代码)(用一个插入排序做对比,可以清楚的看到,小弟我这个快速排序排出的顺序有误)

快速排序问题~~(根据算法导论上的伪代码)(用一个插入排序做对比,可以清楚的看到,我这个快速排序排出的顺序有误)
本帖最后由 xkillercn 于 2012-11-24 22:48:16 编辑
#include<iostream>
using namespace std;

void swap(int * s,int *q){
int *temp;
*temp=*s;
*s=*q;
*q=*temp;
}
int partition(int Before[],int p,int q){ //快速排序关键算法(可能就是这里的错误)
    int x=Before[q];
int i=p-1;
for(int j=p;j<=q-1;j++){
if(Before[j]<=x) i++;
if(i>=p) swap(Before[i],Before[j]);
}
swap(Before[i+1],Before[q]);
return i+1;
}
class Sort{

public:
void InsertSort(int Before[], int n);
void QuickSort(int Before[],int p,int q );
};
void Sort:: InsertSort(int Before[], int n){
  
for(int i=1;i<n;i++){
for(int j=i;j>0;j--){
if(Before[j]<Before[j-1]) 
swap(Before[j],Before[j-1]);
}
}
}

void Sort::QuickSort(int Before[],int p,int q){//递归调用
int t(0);
if (q>p){
t=partition(Before,p,q);
QuickSort(Before,p,t-1);
QuickSort(Before,t+1,q);}
   
}

int main(){
Sort TEST;
int Order[100];// 这个数组不参与排序,保存排序前的数据
int OK[100]; //这个数组参与排序
int count=0;
cout<<"Please input your number."<<endl;
int t(0);
while(cin>>t){ 

if(t=='#') break;
       
Order[count++] = t;

};

/*插入排序*/
for(int i=0;i<count;i++){
OK[i]=Order[i];
}
    cout<<"InsertSort Order:"<<endl;
    TEST.InsertSort(OK,count);
for(int i=0;i<count;i++)
cout<<OK[i]<<"\t";
    cout<<endl;

      /*快速排序*/
       for(int i=0;i<count;i++){
OK[i]=Order[i];
}
TEST.QuickSort(OK,0,count-1);
cout<<"QuickSort Order:"<<endl;
for(int i=0;i<count;i++)
cout<<OK[i]<<"\t";
    cout<<endl;

system("pause");
return 0;
}


------解决方案--------------------
感觉楼主的比我简单。我对算法这方面比较薄弱。看了下快速排序的描述,将你的partition函数重新写了一下。
测试是正常的,不知道你的现在是否可以。

附上修改的代码:
int partition(int Before[],int p,int q){ //快速排序关键算法(可能就是这里的错误)

int key = Before[q];       // key值
int key_t = q;             // key值位置
for ( int i=p, j=q; i<=j; i++,j--)
{
                // 从前往后比较
if ( (Before[i]>key && i<key_t) 
------解决方案--------------------
 (Before[i]<key)&&i>key_t)
{// 和key值比较,如果不等于,则根据大小及位置关系是否交换
swap(Before[i], Before[key_t]);
key_t = i;
}
                // 从后往前比较
if ( (Before[j]<key && j>key_t) 
------解决方案--------------------