Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/wix/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 如何使用霍尔逻辑证明这个二进制搜索算法是正确的?_Algorithm_Binary Search_Correctness_Proof Of Correctness_Hoare Logic - Fatal编程技术网

Algorithm 如何使用霍尔逻辑证明这个二进制搜索算法是正确的?

Algorithm 如何使用霍尔逻辑证明这个二进制搜索算法是正确的?,algorithm,binary-search,correctness,proof-of-correctness,hoare-logic,Algorithm,Binary Search,Correctness,Proof Of Correctness,Hoare Logic,这是算法: // Precondition: n > 0 l = -1; r = n; while (l+1 != r) { m = (l+r)/2; // I && m == (l+r)/2 if (a[m] <= x) { l = m; } else { r = m; } } // Postcondition: -1 <= l < n //前提条件:n>0 l=-1; r

这是算法:

// Precondition: n > 0

l = -1;
r = n;

while (l+1 != r) {
    m = (l+r)/2;

    // I && m == (l+r)/2

    if (a[m] <= x) {
        l = m;
    } else {
        r = m;
    }
}
// Postcondition: -1 <= l < n
//前提条件:n>0
l=-1;
r=n;
而(l+1!=r){
m=(l+r)/2;
//I&m==(l+r)/2
如果(a[m]不变量为

-1 <= l and l + 1 < r <= n and a[l] <= x < a[r]


循环的Post条件,而
循环的Post条件是其延续条件的倒数,因此在您的例子中,它是
!(l+1!=r)
,即
l+1==r
。但根据霍尔的逻辑规则,我必须首先证明前提条件意味着不变量。我怎么做呢?预编码
n>0
,然后两个第一个赋值
l=-1;r=n
导致
l=-1
r=n>0
,然后它显然意味着
l>=-1
l>+1@marcospgp:是的,这几乎是微不足道的:当然
-∞ 你说的是“终止时,l+1=r”,但不变量是
l+1
。不变量不是应该是
l
?你确定吗?不变量应该在循环的任何迭代之前和之后都是真的,并且只能在循环期间不为真。“循环不变量在进入循环和每次迭代后都为真,因此在退出循环时,可以保证循环不变量和循环终止条件。”from
a[l] <= x < a[r] and a[m] <= x implies a[m] <= x < a[r]
a[l] <= x < a[r] and x < a[m] implies a[l] <= x < a[m].
-1 <= l < n and a[l] <= x < a[l + 1].