← 回題庫

卷別

資料結構與演算法(A)

選擇

國立臺灣大學 2022 · 考試 · 第 10 題

考科演算法

(5 points) Consider an integer array AA of size n>0n > 0 with elements A[1],…,A[n]A[1], \dots, A[n], where the first pp elements are positive and the other (n−p)(n - p) elements are negative. The following algorithm calculates pp correctly by calling COMPUTE-P(A,n)\text{COMPUTE-P}(A, n). What loop invariant is maintained for the while loop of the algorithm?

COMPUTE-P(A, len)
1  if A[1] < 0 return 0
2  left = 1, right = len
3  while left < right
4      m = ceiling((left + right) / 2)
5      if A[m] > 0
6          left = m
7      else
8          right = m - 1
9  return left
  • (A)
    left+1≤p≤rightleft + 1 \le p \le right
  • (B)
    left+1≤p≤right−1left + 1 \le p \le right - 1
  • (C)
    left≤p≤rightleft \le p \le right
  • (D)
    left≤p≤right−1left \le p \le right - 1
  • (E)
    none of the other choices

標準解析

AI 生成