int max(int *p, int n)
{
int a=0, b=n-1;
while (__________)
{
if (p[a] <= p[b])
{
a = a+1;
}
else
{
b = b-1;
}
}
return p[a];
}
The missing loop condition is
Correct : F
Given:
A C function to find the maximum value in an integer array p[] of size n (where n ≥ 1):
Initial indices: a = 0, b = n - 1.
Inside the loop, if p[a] ≤ p[b], we do a = a + 1; otherwise, b = b - 1.
Finally, it returns p[a].
To find:
The missing loop condition.
Solution:
Let me understand what the algorithm is doing here.
We have two pointers, a at the start (index 0) and b at the end (index n - 1).
In each iteration, we compare p[a] and p[b].
If p[a] ≤ p[b], the element at a cannot be the strictly unique maximum, so we can safely eliminate it by incrementing a.
If p[a] > p[b], the element at b is definitely not the maximum, so we eliminate it by decrementing b.
So, in every iteration, the search window [a, b] shrinks by 1.
The maximum element will always remain inside the subarray from index a to b.
We need to stop when the search window contains exactly one element, that is, when a = b.
Once a = b, that single remaining element p[a] is our maximum value.
Therefore, the loop must continue as long as there is more than one element left, which means while a ≠ b (or b != a).
Let's check with an example: n = 1.
Initially a = 0, b = 0.
If the condition is b != a, 0 != 0 is false, the loop doesn't execute at all, and it directly returns p[0], which is correct for a single-element array.
Hence, the correct loop condition is b != a.
Answer:
(D) b != a
Similar Questions
Total Unique Visitors