循环不变式

定义:如果某个命题初始为真,并且每次更改后仍然保持该命题为真,则若干次更改后该命题仍然为真;

应用:

假如有三个变量:begin、current、end,将一个数组分成四个区域:

[0,begin):所有数据假设都是1

[beigin,current):所有数据假设都是2

(end,length-1]:所有数据假设都是3

[current,end):未知数据

利用循环不变式:

初始值为:begin=current=0,end=length-1,此时前三个区间都为空集,满足条件;

遍历current,根据current处的元素值做相应的处理,直到区间[current,end)为空,即current=end时循环退出;

上述问题可以延伸为同颜色小球排列的问题:

现有红,白,蓝三种颜色的小球若干,彼此之间混乱排列,先要求将这些小球,按照同颜色排列在一起的规则将它们重新排列;

进而延伸为荷兰国旗问题;

//improvement1

void AllAlgorithms::hollandNationalFlag2(int *a, int length){
    int begin = 0;
    int end = length - 1;
    int curr = 0;
    while (curr <= end) {//until the end is recolosing to the curr
        if (1 == a[curr]) {
            curr ++;
        }
        else if (2 == a[curr]){
            swap(a[curr], a[end]);
            end --;
        }
        else{
            if (curr != begin)
                swap( a[begin], a[curr]);
            begin ++;
            curr ++;//because when begin is not equal to the curr,the begin must be equal to 1,after swapping,both begin and curr are equal to 1,hence,curr ++
        }
    }
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值