Discussion
The following function computes the maximum value contained in an integer array p[] of size n (n \(\ge\) 1).
int max(int *p, int n) {
int a=0, b=n-1;
while (__________) {
if (p[a] \(\lt\)= p[b]) { a = a+1; }
else { b = b-1; }
}
return p[a];
}
The missing loop condition is
Answer: D
The missing condition is b != a.
The function keeps two candidate positions, a from the left and b from the right. At each step it discards the smaller of p[a] and p[b] by moving that index inward, since the smaller one cannot be the maximum. The maximum is always kept between a and b inclusive. The loop must stop when only one candidate remains, that is when a and b meet, and then p[a] is the maximum. So it should run while b != a.
a != n would let a run past b and off the end of the array. b != 0 ignores a and can move b below a. b \(\gt\) (a + 1) stops with two candidates left and returns p[a] without comparing it with p[b], which fails when p[b] is larger, for example for the array {1, 2}.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development