How would I write a loop for this invariant?

前端 未结 1 1997
轻奢々
轻奢々 2021-01-22 01:02

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         


        
1条回答
  •  被撕碎了的回忆
    2021-01-22 01:21

    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[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

    Note: you could write i=i+1 as ++i as well

    0 讨论(0)
提交回复
热议问题