-1

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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
dj1
  • 25
  • 3

2 Answers2

2

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
0

Better is a lose term. As pointed out in the comments

max(max(a,b), max(c,d));

is very concise however there are 3 function calls. It is slightly faster code wise but a lot more coding to write something like:

if (a>b)
{ 
  if (a>c)
  {
     if (a>d)
     {
         return (a);
     }
  }
}

if (b>a)
{ 
  if (b>c)
  {
     if (b>d)
     {
         return (b);
     }
  }
}
if (c>a)
{ 
  if (c>b)
  {
     if (c>d)
     {
         return (c);
     }
  }
}

if (d>a)
{ 
  if (d>b)
  {
     if (d>c)
     {
         return (d);
     }
  }
}
ojblass
  • 21,146
  • 22
  • 83
  • 132
  • 1
    `std::max({a,b,c,d})` – NathanOliver Sep 17 '15 at 19:34
  • 2
    `max` is commonly implemented as a macro, and even if it isn't, it's probably inlined by modern compilers. – EOF Sep 17 '15 at 19:35
  • This code may do more than twice as many comparisons as `std::max` and for some values this code won't reach any of the `return` statements. Just use `std::max` unless profiling shows it's a bottleneck (and it probably isn't). – Blastfurnace Sep 18 '15 at 01:15