-2

重複の可能性:
この不変式のループをどのように記述しますか?

次の 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;}
    }
4

1 に答える 1

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.
于 2012-04-18T04:14:55.840 に答える