How would I write a loop for this invariant?

2020-04-16 06:16发布

问题:

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