(pseudo code)

```
function highest(i, j, k)
{
if(i > j && i > k)
{
return i;
}
else if (j > k)
{
return j;
}
else
{
return k;
}
}
```

I think that works, but is that the most efficient way?

To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares.

```
int ret = max(i,j);
ret = max(ret, k);
return ret;
```

Pseudocode:

```
result = i
if j > result:
result = j
if k > result:
result = k
return result
```

How about

```
return i > j? (i > k? i: k): (j > k? j: k);
```

two comparisons, no use of transient temporary stack variables...

Your current method: http://ideone.com/JZEqZTlj (0.40s)

Chris's solution:

```
int ret = max(i,j);
ret = max(ret, k);
return ret;
```

http://ideone.com/hlnl7QZX (0.39s)

Solution by Ignacio Vazquez-Abrams:

```
result = i;
if (j > result)
result = j;
if (k > result)
result = k;
return result;
```

http://ideone.com/JKbtkgXi (0.40s)

And Charles Bretana's:

```
return i > j? (i > k? i: k): (j > k? j: k);
```

http://ideone.com/kyl0SpUZ (0.40s)

Of those tests, all the solutions take within 3% the amount of time to execute as the others. The code you are trying to optimize is extremely short as it is. Even if you're able to squeeze 1 instruction out of it, it's not likely to make a huge difference across the entirety of your program (modern compilers might catch that small optimization). Spend your time elsewhere.

**EDIT:** Updated the tests, turns out it was still optimizing parts of it out before. Hopefully it's not anymore.

Not sure if this is the most efficient or not, but it might be, and it's definitely shorter:

```
int maximum = max( max(i, j), k);
```

For a question like this, **there is no substitute for knowing just what your optimizing compiler is doing and just what's available on the hardware**. If the fundamental tool you have is binary comparison or binary max, two comparisons or max's are both necessary and sufficient.

I prefer Ignacio's solution:

```
result = i;
if (j > result)
result = j;
if (k > result)
result = k;
return result;
```

because on the common modern Intel hardware, the compiler will find it extremely easy to emit just two comparisons and two `cmov`

instructions, which place a smaller load on the I-cache and less stress on the branch predictor than conditional branches. (Also, the code is clear and easy to read.) If you are using x86-64, the compiler will even keep everything in registers.

Note you are going to be hard pressed to embed this code into a *program* where your choice makes a difference...

I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)

```
#include <iostream>
#include <limits>
inline int max(int a, int b)
{
int difference = a - b;
int b_greater = difference >> std::numeric_limits<int>::digits;
return a - (difference & b_greater);
}
int max(int a, int b, int c)
{
return max(max(a, b), c);
}
int main()
{
std::cout << max(1, 2, 3) << std::endl;
std::cout << max(1, 3, 2) << std::endl;
std::cout << max(2, 1, 3) << std::endl;
std::cout << max(2, 3, 1) << std::endl;
std::cout << max(3, 1, 2) << std::endl;
std::cout << max(3, 2, 1) << std::endl;
}
```

This bit twiddling is just for fun, the `cmov`

solution is probably a lot faster.

```
public int maximum(int a,int b,int c){
int max = a;
if(b>max)
max = b;
if(c>max)
max = c;
return max;
}
```

There is a proposal to include this into the C++ library under N2485. The proposal is simple, so I've included the meaningful code below. Obviously, this assumes variadic templates

```
template < typename T >
const T & max ( const T & a )
{ return a ; }
template < typename T , typename ... Args >
const T & max( const T & a , const T & b , const Args &... args )
{ return max ( b > a ? b : a , args ...); }
```

Similar Questions

Reader's digest version: What is the most efficient way of requesting an image from a server and placing it into the DOM using AJAX (or AJAI, perhaps? : ) )? Here's the long version: Hello SO, I'm set

This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.

I have this string: B82V16814133260 what would be the most efficient way to get two strings out of it: left part String: B82V rigth part string: 16814133260 The rule is this: take all numbers on

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lower and upper? Of course, u

Could you please let me know a query in oracle to find greatest of three columns in 10 rows. The requirement is I have three dates column and I have need to find greatest of three columns in 10 rows.

Using jQuery or straight Javascript, I'm looking for the best way to find the leftmost div (or in general the DOM element with the minimum or maximum position on either axis). So far I have two soluti

I was wondering what is the most efficient way to parse JSON in C#? And by efficient I mean the one with the lower response time. I am trying to parse a large amount of data using a couple of methods,

I would like to know if there's an efficient algorithm to find the greatest m elements in an N x N matrix, with a method header like this: double[] greatestValues(double[][] matrix, int numberOfElemen

What is the fastest and most efficient way to create XML documents in Java? There is a plethora of libraries out there (woodstox, xom, xstream...), just wondering if any one has any input. Should I go

What is the most efficient way to convert a std::vector to a .NET List? To give some context, I am wrapping an unmanaged C++ class with C++/CLI. The C++/CLI class holds a pointer to the C++ class and

I run a website that needs to routinely loop through a bunch of PNGs with transparency's and merge them together. Sometimes this can be a LONG process so I was wondering what is the most efficient way

What is the quickest way for converting a date which is a string with the format 20110913 to 2011-09-13 in Java.

I have a string c1234 -- what's the most efficient and quick way to remove the first letter of a string?

Given a query string Q of length N, and a list L of M sequences of length exactly N, what is the most efficient algorithm to find the string in L with the fewest mismatch positions to Q? For example:

I want to create an application like this: http://typewith.me/2wicOjuefI What is the most efficient way to create this real time application ? Flash ? Long polling ? Http Streaming ? or anything else

I have a table of posts and comments. Posts and comments have a post_id, but comments also have a parent_id that refers to another post in the same table. I'm trying to find the most efficient way

Given the following schema, where members can share ownership of posts: member: id, name, ... post_owner: member_id, post_id post: id, created, ... What's the most efficient query to find users who h

What is the most efficient way to set multiple styling on elements in javascript? for (i=0;i<=lastSelector;i++) { var e = mySelector[i], v = 'opacity 1s'; e.style.WebkitTransition = v; e.style.MozT

I'm just wondering what the opinion is on the most efficient way to migrate data to new schema in SQL server 2008. The database has 7 tables and is 8gb in size. I briefly tried using a .NET app and th

If I have some integer n, and I want to know the position of the most significant bit (that is, if the least significant bit is on the right, I want to know the position of the furthest left bit that

The code below works, but I know it can't be the most efficient. Is there another way to ask if there are any rows rather than using Any()? I'd like to have the NoResults Div hidden by default and onl

Given a string string, what is the fastest/most-efficient way to count lines therein? Will accept best answers for any flavour of Rebol. I've been working under the assumption that the parse [some [th

What is the most efficient way of writing a producer/consumer queue where one thread is the producer and the other is a consumer. In one paper, the author said that it requires one atomic operation to

I'm migrating from Matlab to C + GSL and I would like to know what's the most efficient way to calculate the matrix B for which: B[i][j] = exp(A[i][j]) where i in [0, Ny] and j in [0, Nx]. Notice tha

I've got a PHP page that calls almost the same query three times in the page and wanted to see if there was a quicker way of using this rather than in three seperate instances. the queries are, in ess

So I have some objects each with an integer field group number. I want to find in the most efficient time whether all objects belong to the same group. Can this be done in less than O(n) time in C++ ?

Given a list of assorted length words, what is the best way to find the maximum length of any words? For example, the following should return 6 findMaxLen(a,set,of,random,words) Of course, it's fa

I am curious what the most efficient way is to read a text file (do not worry about size, it is reasonably small so java.io is fine) and then dump its contents into a JTextArea for display. E.g. can

I have an interesting little problem, and I know there are multiple ways to skin the cat but I was wondering what would the best/most efficient way be. Say for example I have an integer with the value

I have three doubles: double[] accel = new double[3] { _Razor.Accel_X, _Razor.Accel_Y, _Razor.Accel_Z, }; What's the most efficient way to find the largest of these in NETMF?

How to compute the greatest number and display it? import java.util.Scanner; public class GreatestNumber { public static void main(String[] args) { int [] num = new int [10]; int counter; int max = 0;

I'm trying to figure out the most efficient/fast way to add a large number of convex quads (four given x,y points) into an array/list and then to check against those quads if a point is within or on t

I have a string that contains some values I need to extract. Each of these values is surrounded by a common character. What is the most efficient way to extract all of these values into an array? For

So apparently calculating square roots is not very efficient, which leaves me wondering what the best way is to find out the distance (which I've called range below) between two circles is? So normal

What is the most efficient way to get live updates from an online sevrer without DDOSing it or slowing down the client application? *I heard about long-polling once but I'm not sure if it's the best w

I have to achieve the following layout in one of my android applications: Edit: I also need the selection of one of the elements to be displayed in a similar way as that: So each of the 3 elements h

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP? Note: I am rewriting an existing system

All these do it, but what is the most efficient way? $(selector).html(''); $(selector).text(''); $(selector).children().remove();

What is the most efficient way to insert one Vector into another at specific position? For example: var aa:Vector.<int> = Vector.<int>([1, 2, 3]); var bb:Vector.<int> = Vector.<in

The code below is supposed to find the numbers in arr_1 that are missing in arr_2. def compare_1 (arr_1, arr_2) output = [] temp = arr_2.each_with_object(Hash.new(0)) { |val, hsh| hsh[val] = 0 } arr_1

Let's say I have three arrays a, b, and c of equal length N. The elements of each of these arrays come from a totally ordered set, but are not sorted. I also have two index variables, i and j. For all

Of the two choices I have to access the value of a control which is the most efficient? getComponent(ControlName).getValue(); or dataSource.getItemValue(FieldName); I find that on occasion the g

I'm in great need of a way to dig through potentially huge amounts of CGI supplied POST data. With reading the GET data it's no big deal, as I can just re-request the QUERY_STRING environment variabl

Is there a known 'most efficient' version of the A* search algorithm? I know some people write papers on the most efficient way to compute common operations, has this been done for A*? specifically th

I have a HashMap where the key is a word and the value is a number of occurrences of that string in a text. Now I'd like to reduce this HashMap to only 15 most used words (with greatest numbers of occ

I am looking for the most efficient way of converting image file to Base64 String in Android. The image has to be sent in a single Base64 String at once to backend. First I use imageToByteArray and th

My map-reduce job writes the final results to sequence files. Is there any efficient way to find the sequence file for a given key?

Let's say I have an array of quantity ranges: [{min=1, max=500}, {min=2, max=1000}, ...] What is the most efficient way to validate that the ranges do not overlap (the above would fail validation)?

I know VBA in Excel isn't the quickest of things - but I need the most efficient (i.e. quickest) way to loop through a large sample of rows. Currently I have: For Each c In Range($A$2:$A$ & Cell

(My apologies, this is a 2nd post to http://stackoverflow.com/questions/3390175/most-efficient-way-to-determine-if-a-string-length-0 but I can't figure out how to reply to people's answers, my reply b