利用快排思想排红绿蓝小球

        对于红绿蓝三种小球这个问题,类似快排中 partition 过程。不过,要用三个指针,一前 begin,一中 current,一后 end,俩俩交换。

    while(current<=end){

        1、 current 指 1 ,current++

        2、 current 指 0,与 begin 交换,而后 current++, begin++,

        3、 current 指 2,与 end 交换,而后, current 不动, end--。

     }

    具体代码:

inline void swap(int &a,int &b){
    int tmp=a;
    int a=b;
    int b=tmp;
}

void Sort_RGB(int a[],int start,int last){
    if(start>=last) return;
    
    int begin=start;
    int current=start;
    int end=last;
    while( current<=end )
    {
        if( array[current] ==0 )
        {
            swap(array[current],array[begin]);
            ++current;
            ++begin;
        }
        else if( array[current] == 1 )
        {
            ++current;
        }
        else //When array[current] =2
        {
            swap(array[current],array[end]);
            --end;
        }
    }
    //最终begin指向第一个绿球,current指向第一个蓝求
    return;
}

优化写法(其实也不优化,但是能够减少交换次数):

inline void swap(int &a,int &b){
    int tmp=a;
    int a=b;
    int b=tmp;
}

void Sort_RGB(int a[],int start,int last){
    if(start>=last) return;
    
    int begin=start;
    int current=start;
    int end=last;
    while( current<=end )
    {
        if( array[current] ==0 )
        {
            swap(array[current],array[begin]);
            while(array[++current]==1){};//找到非绿球
            begin++;
        }
        else if( array[current] == 1 )
        {
            while(array[++current]==1){};//找到非绿球为止
        }
        else //When array[current] =2
        {
            swap(array[current],array[end]);
            while(array[--end]==2){};//找到非蓝球为止
        }
    }
    //最终begin指向第一个绿球,current指向第一个蓝求
    return;
}


转载于:https://my.oschina.net/zengjs275/blog/659100

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值