三向切分的快速排序

来源:互联网 发布:塞尔维亚 知乎 编辑:程序博客网 时间:2024/04/29 10:42
对于存在大量重复元素的数组,这种方法比标准的快速排序的效率高得多。
#include<iostream>using namespace std;int partition(int a[],int lo,int hi){    int i=lo,j=hi+1;    int v=a[lo];    while(true){        while(a[++i]<v)if(i==hi)break;        while(v<a[--j])if(j==lo)break;        if(i>=j)break;        int temp=a[i];        a[i]=a[j];        a[j]=temp;    }    int temp=a[lo];    a[lo]=a[j];    a[j]=temp;    return j;}void sort(int a[],int lo,int hi){    if(hi<=lo)  return;    int j=partition(a,lo,hi);    sort(a,lo,j-1);    sort(a,j+1,hi);}void quick3way(int a[],int lo,int hi){    if(hi<=lo)return;    int lt=lo,i=lo+1,gt=hi;    int v=a[lo];    while(i<=gt){        int temp;        if(a[i]>v){            temp=a[i];            a[i]=a[gt];            a[gt]=temp;            gt--;        }        else if(a[i]<v){            temp=a[lt];            a[lt]=a[i];            a[i]=temp;            lt++;            i++;        }        else if(a[i]=v) i++;    }    sort(a,lo,lt-1);    sort(a,gt+1,hi);}int main(){    int a[5]={5,3,4,1,2};    quick3way(a,0,4);    for(int i=0;i<5;i++)        cout<<a[i];    cout<<endl;    return 0;}

0 0
原创粉丝点击