c++ - Comparing 3 number properties of an object -
i wanted know fastest , efficient way of comparing 3 numerical properties of number , determining lowest value , highest value. have object following prop
obj.a = 5; obj.b = 13; obj.c = 2; now need calculate lowest value(2) , highest value(13);
one option have using conditional statement having 3 conditions checking greatest element , 3 lowest element.resulting in 6 conditional statements.my other option pushing these values in vector , retrieving extreme values sorted vector. there alternative approach ? suggestions ?
create min() function 2 variables as:
int min(int x, int y) { return y ^ ((x ^ y) & -(x < y)); } similarly max 2 variables as:
int max(int x, int y) { return x ^ ((x ^ y) & -(x < y)); } and call function 3 variables as:
int max = max(a,max(b,c)); int min = min(a,min(b,c)); these methods quite efficient , may used number of variable comparison.
it uses concept
the xor of number 0
xor of number 0 number itself.
again can used nested calls n number of number comparisons.
note: may replace x<y x-y>>31 (considering x 32 bit signed integer).
i sure cannot more efficient 3 numbers
Comments
Post a Comment