Using min / max values ​​of a type when searching for min / max values ​​in a set

Initially, I basically wrote an essay with a question at the end, so I'm going to squeeze it into this: which is better (being really insignificant here)?

AND)

int min = someArray[0][0];
for (int i = 0; i < someArray.length; i++)
    for (int j = 0; j < someArray[i].length; j++)
        min = Math.min(min, someArray[i][j]);

-or -

AT)

int min = int.MAX_VALUE;
for (int i = 0; i < someArray.length; i++)
     for (int j = 0; j < someArray[i].length; j++)
         min = Math.min(min, someArray[i][j]);

I believe that b is faster by storing an instruction or two, initializing with a minconstant value instead of using an indexer. He also feels less redundant - not comparing someArray[0][0]with himself ...

Like an algorithm that is better / fair-er.

EDIT: Suppose the array is not null, not empty.
EDIT2: Fixed several careless errors.

+3
source share
3 answers

(, , ). , A , ( , ) .

, , , semilattice. , max, :

  • max idempotent, , , : max (x, x) = x
  • max , , : max (x, y) = max (y, x)
  • max , , : max (max (x, y), z) = max (x, max (y, z) )

, . , , " " . , union intersection, , .

(, , ..) , (, ), , . ( , ).

, , , () , , , , :

Element e = data[0];
for (i in data[1 .. n])
    e = meet(e, data[i])

, , , , , , . , , , .. "max" "min", , , max min.

, . , , . , ,

min(int.MAX_VALUE, x) = min(x, int.MAX_VALUE) = x

, int.MAX_VALUE , . , int.MAX_VALUE . ( & top;),

meet (& top;, x) = meet (x, & top;) = x

max min, int.MIN_VALUE,

max(int.MIN_VALUE, x) = max(x, int.MIN_VALUE) = x

& top; , , ,

Element e = Element.TOP;
for (i in data[0 .. n])
    e = meet(e, data[i])

, e meet(e, data[0]) = meet(Element.TOP, data[0]) = data[0], , . , , ; , .

, . , , ,

meet(x, y) = x if x lexicographically precedes y
           = y otherwise

, meet("a", "ab") = "a", meet("dog, "cat") = "cat" .. s, property (s, x) = meet (x, s) = x, . , , .

, , , . , , , & top; , meet (& top;, x) = meet (x, & top;) = x. , , .

, ,

bool found = false;
Element e;

for (i in data[0 .. n]) {
    if (!found) {
        found = true;
        e = i;
    } else {
        e = meet(e, i);
    }
}

, found , . , , e - . , , e .

, ! , ... .: -)

+1

B ; someArray , ; A B , someArray null ( ), A B .

0

From a practical point of view, I like option A slightly better, because if the data type is being processed in the future, changing the initial value is another thing that needs to be updated (and, therefore, one thing that may go wrong).

In terms of algorithmic purity, I have no idea if anyone else is better.

By the way, option A should have its initialization as follows:

int min = someArray[0][0];
0
source

Source: https://habr.com/ru/post/1783325/


All Articles