75.4k views
4 votes
C++ Write a recursive function that returns both the smallest and the largest

element in an int array. Also, write a program to test your function

1 Answer

1 vote

Final answer:

To solve the problem, a recursive C++ function named findMinMax is necessary. It has parameters to track the smallest and largest values while traversing subdivisions of the array. A main program initializes the array, invokes findMinMax, and displays the result.

Step-by-step explanation:

To write a recursive function that returns both the smallest and largest elements in an integer array in C++, you will need to pass additional parameters that maintain the state of the smallest and largest elements found so far in each recursive call. Here is an example of how you might implement such a function:

void findMinMax(int arr[], int low, int high, int &min, int &max) {
if (low == high) { // If there's only one element
if (arr[low] < min) min = arr[low];
if (arr[high] > max) max = arr[high];
return;
}
if (high - low == 1) { // If there are two elements
if (arr[low] < arr[high]) {
if (arr[low] < min) min = arr[low];
if (arr[high] > max) max = arr[high];
} else {
if (arr[high] < min) min = arr[high];
if (arr[low] > max) max = arr[low];
}
return;
}
// If there are more than two elements
int mid = (low + high) / 2;
findMinMax(arr, low, mid, min, max); // Recursive call for first half
findMinMax(arr, mid + 1, high, min, max); // Recursive call for second half
}

To test your function, you could write a main program that initializes an array, calls the findMinMax function, and then prints out the smallest and largest elements:

int main() {
int arr[] = {5, 1, 9, 3, 2, 8, 4};
int min = INT_MAX;
int max = INT_MIN;
int size = sizeof(arr) / sizeof(arr[0]);
findMinMax(arr, 0, size - 1, min, max);
std::cout << "Smallest: " << min << "\\Largest: " << max << std::endl;
}

User Jason Jarrett
by
8.0k points