Problem Statement
Write a program to find the minimum and maximum elements in an array using recursion. You cannot use loops or built-in functions like min()
or max()
. The solution should recursively compute the minimum and maximum by dividing the problem into smaller subproblems.
Input:
- A non-empty array of integers,
arr
. - An integer,
n
, representing the size of the array.
Output:
- The minimum element in the array.
- The maximum element in the array.
Examples
Example 1:
Input: arr = [3, 5, 1, 8, -2, 7], n = 6
Output: Minimum element = -1
Maximum element = 8
Example 2:
Input: arr = [10], n = 1
Output: Minimum element = 10
Maximum element = 10
Different Approaches
1️⃣ Recursion
Algorithm:
- Base Case:
- If the array has only one element, return it as both the minimum and maximum.
- Recursive Case:
- Compare the last element of the array with the result of the recursive call on the rest of the array to find the minimum and maximum.
Code:
#include <iostream>
#include <vector>
#include <climits> // For INT_MIN and INT_MAX
using namespace std;
// Recursive function to find the minimum element in the array
int findMin(const vector<int>& arr, int n) {
// Base case: If there's only one element, return it as the minimum
if (n == 1) {
return arr[0];
}
// Recursive case: Find the minimum of the rest of the array
return min(arr[n - 1], findMin(arr, n - 1));
}
// Recursive function to find the maximum element in the array
int findMax(const vector<int>& arr, int n) {
// Base case: If there's only one element, return it as the maximum
if (n == 1) {
return arr[0];
}
// Recursive case: Find the maximum of the rest of the array
return max(arr[n - 1], findMax(arr, n - 1));
}
int main() {
vector<int> arr = {3, 5, 1, 8, -2, 7}; // Input array
int n = arr.size(); // Size of the array
// Find and print the minimum and maximum elements using recursion
cout << "Minimum element: " << findMin(arr, n) << endl;
cout << "Maximum element: " << findMax(arr, n) << endl;
return 0;
}