Open In App

C++ Program to Find the Minimum and Maximum Element of an Array

Last Updated : 17 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, write functions to find the minimum and maximum elements in it. 

Example:

C++




// C++ program to find minimum (or maximum) element 
// in an array. 
#include <bits/stdc++.h> 
using namespace std; 
  
int getMin(int arr[], int n) 
    return *min_element(arr, arr + n); 
  
int getMax(int arr[], int n) 
    return *max_element(arr, arr + n); 
  
int main() 
    int arr[] = { 12, 1234, 45, 67, 1 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    cout << "Minimum element of array: " << getMin(arr, n) << " "
    cout << "Maximum element of array: " << getMax(arr, n); 
    return 0; 


Output: 

Minimum element of array: 1
Maximum element of array: 1234

Time Complexity: O(n)

Auxiliary Space: O(1), as no extra space is used

Recursive Solution 

Example:

C++





Output: 

Min of array: 1
Max of array: 1234

Time Complexity: O(n)

Auxiliary Space: O(n), as implicit stack is used due to recursion

Using Library functions: 
We can use min_element() and max_element() to find minimum and maximum of array. 

Example:

C++




// C++ program to find minimum (or maximum) element 
// in an array. 
#include <bits/stdc++.h> 
using namespace std; 
  
int getMin(int arr[], int n) 
    return *min_element(arr, arr + n); 
  
int getMax(int arr[], int n) 
    return *max_element(arr, arr + n); 
  
int main() 
    int arr[] = { 12, 1234, 45, 67, 1 }; 
    int n = sizeof(arr) / sizeof(arr[0]); 
    cout << "Minimum element of array: " << getMin(arr, n) << " "
    cout << "Maximum element of array: " << getMax(arr, n); 
    return 0; 


Output:

Minimum element of array: 1
Maximum element of array: 1234

Time Complexity: O(n)

Auxiliary Space: O(1), as no extra space is used

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads