For a large number of elements, the Standard Library has the std::max_element
algorithm which does max(N-1, 0)
comparisons for N
elements, which his the theoretical minimum, even for 4 elements.
In practice, it loops over all elements as does your method 1., but it could do an "elimination tournament" of nested max
if N
is a power of 2 (your method 2). Some optimizing compiler might even unroll the loop and produce a complicated chain of if
statements (your method 3).
In the comments, the C++11 style solution max({a,b,c,d})
was given by @NathanOliver (which only works in constexpr
contexts). But in C++1z, the std::max_element
will also become constexpr
so that it will be the fully general solution, small or large, runtime or compile-time.
TL;DR: don't overthink this, use the Standard Library which does provably minimal amount of work.