Arun
Arun

Reputation: 121

How to find the maximum and minimum value in an array without using if statement?

How to find the maximum and minimum value in an array without using if statement.Are there any built in function in to do so in c++? If not is insertion sort the only way?Thanks in advance.

Upvotes: 2

Views: 2488

Answers (2)

Ilya
Ilya

Reputation: 4689

First of all, you can implement function sort(a, b), which returns pair of sorted values. To do it you can use following idea: min(a, b) = (a+b)/2 - |a-b|/2 and max(a, b) = (a+b)/2 + |a-b|/2.

But here you have function |x|=abs(x), which uses 'if' inside. So, we should implement 'abs' without any 'if'. One of the simpliest ways is following: abs(x) = sqrt(x*x) (it is very slow, but it is only an idea). For integer values you can use these approaches: 1, 2, etc.

So, you can implement function sort(a,b) which sorts only pair of values without any 'if'. After it you can use this function to sort the array. After it first element of that sorted array will be minimum value and last element will be maximum element.  

Upvotes: 1

ForEveR
ForEveR

Reputation: 55887

Use std::minmax_element if you use C++11, or std::min_element/std::max_element if no.

std::vector<int> v = {1,2,3,4};
auto minmax = std::minmax_element(v.begin(), v.end());
// now minmax.first points on 1 and minmax.second points on 4

However, if if condition should not be used internally - you can use following thing

template<typename Iterator>
std::pair<Iterator, Iterator> minmax_element(Iterator first, Iterator last)
{
   Iterator min = first, max = first;
   while (first != last)
   {
      min = *min > *first ? first : min;
      max = *max > *first ? max : first;
      ++first;
   }
   return std::make_pair(min, max);
}

Upvotes: 4

Related Questions