How would I write a loop for this invariant?

我与影子孤独终老i 提交于 2019-12-02 02:38:56

问题


These are assertions for an algorithm to find the minimum of an array b[h.k]:

Precondition: h <= k < b.length
Postcondition: b[x] is the minimum of b[h...k]

Is this the correct loop for this invariant?

invariant: b[x] is the minimum of b[h...t]

int x = t;    int t = h;
// {inv: b[x] is the minimum of b[h...t]}
while (t != k) {
   t = t+1;
   if (b[t] < b[x])
      { x = t;}
}

回答1:


You can find the minimum of an array this way (pseudocode):

// assume b.length > 0
min = b[0]
for i=1 to b.length
  if b[i] < min
    min = b[i]

To restrict it to b[h, ..., k]:

min = b[h]
for i=h+1 to k
  if b[i] < min
    min = b[i]

So you basically just change the upper and lower bound of the loop

Since h<=k<b.length, b[h] is valid and executing the loop from the next element until k iterates over the reqiured elements (if h==k, the loop is empty)

UPDATE: as you are consistently failing with the implementation of the pseudocode into java, I'll translate it for you:

// assume: int b[]; int h; int k; h<=k<=b.length and b.length>0
// find min == b[i] such that b[i]<=b[j] for all h<=j<=k
int min = b[h];
for (int i=h+1; i<k; i=i+1) {
  if (b[i] < min) {
    min = b[i];
  }
}
// here: min contains the (first) minimum element within b[h, ..., k]

Note: you could write i=i+1 as ++i as well



来源:https://stackoverflow.com/questions/10202004/how-would-i-write-a-loop-for-this-invariant

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!