Machine-translated by Google. Questions are authored in English.
Top

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

  • A.a != n
  • B.b != 0
  • C.b \(\gt\) (a + 1)
  • D.b != a

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}.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.