开发者

Implementing array with min-value ints

I currently have a nxn array of ints. I plan to initialize all the cells within the array with infinity and later change it if a value being compared to the cell is lower than the value inside the cell. Here is the pseudo-code of what I came up with so far, using -1 to represe开发者_运维问答nt infinity. What do you think? Is this the most efficient way, any bugs?

if(table[i][j] == -1 || (table[i][j] != -1 && table[i][j] > value)
    then table[i][j] = value


I would instead start with Integer.MAX_VALUE. This way, the code could be simpler :

if(table[i][j] > value) {
     table[i][j]=value;
}

Notice that, were your array to contain doubles, you could even go as far as using Double.POSITIVE_INFINITY.


If you are sure that the value -1 can be treated as a "reserved" value, you should be fine with such approach.

You could also consider encapsulating the datatype in some PossiblyInfinitInteger which has a boolean of whether or not it is set to infinity. Perhaps an overkill, I don't know.


  1. if(table [i][j] == -1 || table[i][j] > value) then ... does the same. I'm not sure, but the compiler may take care of this.
  2. If -1 is reserved, and the values cannot be less than 0, your approach is correct, just compare table[i][j] < value and not visa versa.
  3. If using -1 as a reserved value is a problem, use Integer.MAX_VALUE: if(table[i][j] == Integer.MAX_VALUE) then table[i][j] = value;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜