以下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;}
}
答案 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.