How to write an efficient maximum function?

A

Alex Hunsley

Boudewijn said:
That method always runs in the same amount of VM ticks. It takes:
- 3 comparisons;
- 3 copies; and
- 3 jumps.

How about:

private static float maximum(float a, float b, float c, float d)
{
float max = a;
if (b > max) max = b;
if (c > max) max = c;
if (d > max) max = d;
return max;
}

which takes:
- 1..4 copies;
- 3 comparisons; and
- 3 jumps.

The average number of copies is calculated as follows:
if a is maximum: 1 copy
if b is maximum: 2 copies
if c is maximum: 3 copies
if d is maximum: 4 copies
average copies = (1 + 2 + 3 + 4) / 4 = 10 / 4 = 2.5

Note that 2.5 < 3

I was going to suggest the same code structure as you wrote, but merely
because it's much more readable and obvious if you've written it wrong!
 
T

Thomas G. Marshall

Jesper Nordenberg coughed up:
I've only found one that is optimal for integers:

private static int maximum(int a, int b, int c, int d) {
for (int i=Integer.MIN_VALUE; i<=Integer.MAX_VALUE; i++) {
if (i > a && i > b && i > c && i > d)
return i - 1;
}

throw new RuntimeException("Something is wrong with your
integers!"); }


Sorry, bad joke ;-)

/Jesper Nordenberg


I think a thread on how to write the worst max function would be the most
interesting of all!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top