Write a recursive algorithm in a pseudo code, Min-Max, for finding both the minimum and the maximum elements in an array A of n elements. Your algorithm calls itself only once within the algorithm and should return a pair (a, b) where a is the minimum element and b is the maximum element.
Algorithm Min-Max(A, n)
Input: an Array A of n elements
Output: a pair of (a, b) where a is the minimum element and b is the maximum element
HERE IS THE CODE FOR YOU :
//Explanation has been done in the code as u already know the concept of basic searching
/*************************************************/
#include <bits/stdc++.h>
using namespace std;
// globally declaring a pair
pair<int,int> comb;
// function returning a pair
pair<int,int> func(int arr[],int n){
if(n==0) return comb;
// assigning new minimum values to the pair
comb.first=min(comb.first,arr[n-1]);
// assigning new maximum values to the pair
comb.second=max(comb.second,arr[n-1]);
return func(arr,n-1);
}
int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
// after all the iterations first will contain minimum
element
// where as second will contain maximum element
comb=make_pair(INT_MAX,INT_MIN);
// recieving new pair in p
pair<int,int> p=func(arr,n);
// printing result
cout<<"MINIMUM ELEMENT "<<p.first<<endl;
cout<<"MAXIMUM ELEMENT "<<p.second<<endl;
return 0;
}
SOME OUTPUTS
Get Answers For Free
Most questions answered within 1 hours.