快速实施

dat*_*ili 6 c++ quicksort

以下代码为quicksort不起作用,我无法理解是什么原因.

#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
    int s=a[i];
    a[i]=a[j];
    a[j]=s;

}
int  partition(int a[],int l,int h);
void quick(int a[],int l,int h){
    if (h<=l) return ;
    int j=partition(a,l,h);
    quick(a,l,j-1);
    quick(a,j+1,h);
    }
int partition(int a[],int l,int h){
    int i=l-1;
    int j=h;
    int v=a[l];
    while(true){

        while( a[++i]<v);

        while(a[--j]>v) if (j==i)  break;

            if (i>=j) break;

        exch(a,i,j);

    }

    exch(a,i,h);
    return i;



}
int main(){

    int a[]={12,43,13,5,8,10,11,9,20,17};
    int n=sizeof(a)/sizeof(int);
quick(a,0,n-1);
 for (int  i=0;i<n;i++){
     cout<<a[i]<<"  ";
 }
     return 0;
 }
Run Code Online (Sandbox Code Playgroud)

它输出

5  8  9  11  10  17  12  20  13  43
Run Code Online (Sandbox Code Playgroud)

Mit*_*eat 7

在你的partition方法中,应该是

int v = a[h]; 
Run Code Online (Sandbox Code Playgroud)

不是

int v = a[l];
Run Code Online (Sandbox Code Playgroud)

[更新:我刚刚使用该更改测试了代码,并且它正常工作,输出:

5  8  9  10  11  12  13  17  20  43 
Run Code Online (Sandbox Code Playgroud)