Consider the following function definition
int Trial (int a, int b, int c)
{
if ((a>=b) && (c<b)) return b;
else if (a>=b) return Trial(a, c, b);
else return Trial(b, a, c);
}
The functional Trial:
View worked solution
Answer: D
Let us analyze the behavior of the function Trial(a, b, c):
- Base Case: The condition
(a >= b) && (c < b)represents the ordering . In this case, is the middle (median) element, and the function correctly returns . - Recursive Step 1: If , the function calls
Trial(b, a, c)to swap and so that the first argument is greater than or equal to the second. - Recursive Step 2: If but , the function calls
Trial(a, c, b)to swap and .
However, the function fails to terminate for certain inputs where . For example, consider Trial(2, 1, 1):
- Since () is true but () is false, the base condition is not met.
- The
else if (a >= b)condition () is true, so it callsTrial(a, c, b), which isTrial(2, 1, 1). - This results in an infinite recursion (stack overflow).
Since the function does not terminate for all inputs, it does not correctly find the middle number. Thus, the correct option is D.
Free practice · Your answers on this page are not saved.
