← AP CSP Course← AP CSP 课程 ← Back to Study Guide← 返回学习指南

Trace binary search逐步追踪二分查找

Run one AP CSP pseudocode statement or condition check at a time. Watch nums, target, low, high, mid, and found change.每次执行一条 AP CSP 伪代码语句或检查一次条件,观察 nums、target、low、high、mid、found 的变化。

Code代码

  1. nums ← [2, 4, 6, 8, 10, 12, 14]
  2. target ← 12
  3. low ← 1
  4. high ← 7
  5. found ← false
  6. REPEAT UNTIL (low > high OR found) {
  7. mid ← (low + high) / 2
  8. IF (nums[mid] = target) {
  9. found ← true
  10. DISPLAY(mid)
  11. } ELSE {
  12. IF (target < nums[mid]) {
  13. high ← mid - 1
  14. } ELSE {
  15. low ← mid + 1
  16. }
  17. }
  18. }

State状态

Variable变量Value值
nums[2, 4, 6, 8, 10, 12, 14]
target—
low—
high—
mid—
found—
Condition条件—
Output输出—

Use ← and → to step. The note explains each comparison and change.使用 ← 和 → 逐步运行。每次比较和变化见下方说明。