How would I write a loop for this invariant?

点点圈 提交于 2019-12-02 01:52:34

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

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