To prepare a video lecture on min and max functions, I would like to learn from the community about fundamentally different ways of implementing these functions, which I don’t know about. Fundamentally different - they are different in their logical sense, and not in implementation. I will write what I know, and in the answers I ask you to write what I could miss. Let's consider only signed numbers, with unsigned, the general principle is the same, but the formulas are slightly different.
First , the usual comparison:
max = a>b?a:b; min = a<b?a:b;
Second : first we define the function doz (a, b), which is equal to ab, if a> = b, and zero otherwise. This function can be implemented in many ways:
doz = a>=b?ab:0;
or
doz = (ab)&-(a>=b)
or
d = ab; doz = (d&(~(d^((a^b)&(d^a))) >> 31));
Then just write:
max = b + doz(a,b); min = a - doz(a,b);
or by combining ideas:
max = ((a^b)&-(a>=b))^b; min = ((a^b)&-(a<=b))^b;
Third : if we know for sure that there will be no overflow or borrowing during intermediate calculations, then we assume that doz is:
doz = (ab)&~((ab)>>31);
at the same time, min and max are calculated using doz as above.
Fourth : we also assume that the difference and the sum do not overwhelm the variables:
max = (a+b)/2 + abs(ab)/2; min = (a+b)/2 - abs(ab)/2;
At the same time, we implement the abs function in a variety of ways (several options can be found here ), this does not change the idea.
This is all I know (I hope I didn’t make any typos). Are there any other ways that differ from these fundamentally, that is, not by rearranging operations or replacing some actions with similar ones (otherwise you can still make a dozen formulas), namely the very idea? This is what I ask to share.