简体   繁体   中英

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.

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);
}

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 - |ab|/2 and max(a, b) = (a+b)/2 + |ab|/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM