Search code examples
c++calgorithmtime-complexityspace-complexity

Which is a better way of finding the max of no.s?


Which is a better way to write a program to find the max of 4 no.s in c/C++:

  1. using a fifth variable & comparing it to all inputs
  2. using max() function
  3. and comparing the inputs using if

or suggest any other, if it has a better approach(in terms of space & time complexity) of solving the problem

Would the same algorithmic approach would still be the best in case of more than 4 variables?


Solution

  • 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.