以下循环对于不变量是否正确?

时间:2012-04-18 03:42:49

标签: java loops

  

可能重复:
  How would I write a loop for this invariant?

以下for循环对于不变量是否正确? 不变量:b [x]是b [h ... s-1]

的最小值
 int x = h;      int h = s-1;

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

1 个答案:

答案 0 :(得分:2)

如果你想找到一个最小的数组,你可以这样做。

int b[] = {1,3,2,5,2,3};

//min needs to have a starting value so b[0] works fine.
int min = b[0];

//This loops over the remaining elements in the array. If it finds a value smaller than the current minimum, it reassigns min to that value.
for(int i = 1; i < b.length; i++)
{
     if(b[i] < min)
          min = b[i];
}

//If you haven't covered for loops yet, here is how you can do it with a while.
int i = 1;
while(i < b.length)
{
     if(b[i] < min)
          min = b[i];
     i++;
}

//b.length is just a way of getting the length of an array.