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

时间:2016-10-26 12:38:49

标签: 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

我做了一些研究,并将不变量缩小到if x is in a[0 .. n-1] then a[l] <= x < a[r]

我不知道如何从那里进步。前提条件似乎过于宽泛,因此我无法显示P -> I

非常感谢任何帮助。这些是可用于证明算法正确性的逻辑规则:

Logic rule for conditionals

Logic rule for loops

1 个答案:

答案 0 :(得分:1)

不变量是

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

隐含约定a[-1] = -∞a[n] = +∞

然后在if声明中

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].

在任何一种情况下,作业都会建立a[l] <= x < a[r]

同时,-1 <= l and l + 1 < r <= n会确保-1 < m < n,以便可以对a[m]进行评估。

终止后,l + 1 = r和不变的

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