c++ - 快速排序实现

标签 c++ 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;
 }

输出

5  8  9  11  10  17  12  20  13  43

最佳答案

在你的partition方法中,应该是

int v = a[h]; 

并且不是

int v = a[l];

[更新:我刚刚测试了更改后的代码,它工作正常,输出:

5  8  9  10  11  12  13  17  20  43 

关于c++ - 快速排序实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7624843/

相关文章:

c++ - 在不使用数组的情况下对二进制文件中的数据进行排序

java - 当数组可能包含也可能不包含枢轴元素时就地分区

c++ - 随机快速排序 [某些输入崩溃]

c++ - QuickSort 比 std::sort 慢

c++ - 排序给出最后位置元素的错误输出

c++ - 错误 C2782 : 'const _Ty &std::min(const _Ty &,const _Ty &)' : template parameter '_Ty' is ambiguous

c++ - 使用 C++,是否有一种安全合法的方法来为涉及多重和虚拟继承的类层次结构实现 “safe cast”,而无需 RTTI?

c++ - C++ 中的线程 : cannot convert argument 1 from 'const std::ofstream' to 'std::ofstream &'

c++ - std::map 插入陷入无限循环或给出访问冲突错误

c - 3 路快速排序(C 实现)