Magazine

How to Find the Minimum and Maximum Element of an Array in C++?

Posted on the 13 May 2021 by Amit Kumar @buddymantra

In this article, you’ll be learning how you can find the minimum and maximum element of an Array using STL in C++ Given an array arr[], find the minimum and maximum element of this array using STL in C++.Example: Input: 1, 11, 2, 4, 19, 22, 34, 56, 71, 23, 2, 0, 53 Output: min = 0, max = 71 Approach 1: Linear Comparisons  Consider the first element as the minimum and maximum  From the second element onwards compare each element with the minimum and maximum. If the element is less than the minimum, then make it as the new minimum. If the element is greater than the maximum, then make it as the new maximum. Number of comparisons in worst case: 2(n-1) Approach 2: Pair-wise Comparisons If the size of array is odd, then assign first element as minimum and maximum If the size of array is even, then compare the first two elements, make the larger element as maximum and smaller element as minimum. From the third element onwards consider two elements at a time and compare them, then compare the lager element with maximum and smaller one with the minimum. Number of comparisons in worst case: 3/2(n-1) + 1 Also Read Introduction to C++ STL Basic Operations on Matrices in C++ Basic Operations on Matrices in C++ Five Ways to Calculate Power in C++ How to reverse an Array in C++?


Back to Featured Articles on Logo Paperblog