Practical Techniques for Writing and Modifying Algorithms | 算法的编写与修改实用技巧

📚 Practical Techniques for Writing and Modifying Algorithms | 算法的编写与修改实用技巧

Algorithms are the heart of computer science. In the CIE A Level Computer Science examination, candidates are often required not only to understand existing algorithms but also to write new ones and modify given pseudo-code to solve problems efficiently. This article provides a structured guide to mastering these essential skills.

算法是计算机科学的核心。在 CIE A Level 计算机科学考试中,考生不仅需要理解现有算法,还需具备编写新算法以及修改给定伪代码以高效解决实际问题的能力。本文将提供一套系统化的方法来掌握这些关键技能。


1. Understanding the Problem Statement | 理解题意

Before writing a single line of pseudo-code, you must understand what the problem is truly asking. Read the question carefully and identify the inputs, outputs, and constraints. Underline key phrases such as ‘for each element’, ‘find the maximum’, or ‘repeat until’. This step is critical because many students lose marks by solving the wrong problem.

在编写任何一行伪代码之前,你必须真正理解问题在问什么。请仔细阅读题目,明确输入、输出和约束条件。在诸如”对于每个元素”、”查找最大值”或”重复直到”等关键短语下方划线。这一步至关重要,因为许多学生因答非所问而失分。

When modifying an existing algorithm, begin by drawing a trace table to examine exactly what the current code does. Identify which parts are correct and which parts cause incorrect outputs. This is especially important in exam questions where a bug is intentionally placed for you to find.

在修改现有算法时,应首先绘制追踪表来深入检查当前代码的实际行为。分辨出哪些部分是正确的、哪些部分导致了错误输出。这在考试题目中尤为重要,因为出题者往往会在代码中故意设置一个需要你来发现的错误。

  • Identify the required inputs and their data types (integer, string, boolean).
  • 确定输入及其数据类型(整型、字符串、布尔型)。
  • Determine the expected outputs and the format in which they must be presented.
  • 确定预期输出及其呈现格式。
  • Note any constraints: array size, value ranges, recursion limits, or time complexity requirements.
  • 记录一切约束条件:数组长度、数值范围、递归深度或时间复杂度要求。

2. Mastering Pseudo-Code Conventions | 掌握伪代码规范

The CIE examination uses a specific pseudo-code convention that includes commands like INPUT, OUTPUT, IF…THEN…ELSE…ENDIF, WHILE…ENDWHILE, REPEAT…UNTIL, FOR…ENDFOR, and CASE…ENDCASE. You must know these structures inside out.

CIE 考试采用一套标准伪代码约定,包括 INPUTOUTPUTIF…THEN…ELSE…ENDIFWHILE…ENDWHILEREPEAT…UNTILFOR…ENDFOR 以及 CASE…ENDCASE 等命令。你必须对这些结构了如指掌。

Array indexing in CIE pseudo-code starts at 1, not 0. This is a common source of off-by-one errors. Always write DECLARE arrayName : ARRAY[1:n] OF INTEGER to declare an array, where n is the number of elements. For 2D arrays, the notation is ARRAY[1:rows, 1:cols].

CIE 伪代码中的数组下标从 1 开始,而非 0。这是”差一错误”的常见来源。声明数组时务必使用 DECLARE arrayName : ARRAY[1:n] OF INTEGER,其中 n 为元素的个数。对于二维数组,使用 ARRAY[1:rows, 1:cols] 表示法。

Use (or = in printed materials) for assignment and == for comparison. In your exam answer, be consistent with the symbols you use. The marker should never have to guess whether you mean assignment or equality.

使用 (在印刷材料中也可写作 =)表示赋值,使用 == 表示相等比较。在考试作答中,务必保持符号使用的一致性。阅卷人不应该需要猜测你的代码中某个符号究竟表示赋值还是比较。

  • Always use ENDIF to close every IF statement.
  • 每个 IF 语句必须以 ENDIF 结尾。
  • Always specify the step in a FOR loop if it is not +1 (e.g., FOR i ← 1 TO n STEP 2).
  • FOR 循环步长不为 +1(例如 FOR i ← 1 TO n STEP 2),则必须明确写出。
  • Use indentation to make nested structures visually clear.
  • 使用缩进使嵌套结构一目了然。

3. Designing Algorithms with Top-Down Thinking | 自顶向下设计算法

When writing an algorithm from scratch, break the problem into smaller sub-problems. Suppose you need to find a student’s grade from a mark. The sub-problems are: receive the input, validate the input, and compute the grade using a CASE statement. Solving each sub-problem separately produces a cleaner and more traceable algorithm.

在从零开始编写算法时,应将大问题拆解为若干小问题。例如,假设你需要根据分数计算学生的等级,子问题包括:读取输入、验证输入、使用 CASE 语句计算等级。逐一解决每个子问题,将得到更简洁、更易于追踪的算法。

A useful strategy is to write comments in English first describing each step, then translate those comments into pseudo-code. This ensures you maintain a logical flow and do not skip essential steps. Comments in pseudo-code are written using the comment symbol // in CIE convention.

一个实用的策略是先用英语写出描述每个步骤的注释,再将注释翻译为伪代码。这样可以确保逻辑流畅并无遗漏关键步骤。CIE 约定中,伪代码的注释符号为 //

Consider the following simple design: to find the largest value in a list, initialise a variable max with the first element, then iterate through the remaining elements, updating max whenever a larger value is found.

考虑以下简单设计:若要找出列表中的最大值,可先将第一个元素赋给变量 max,然后遍历剩余元素,每遇到更大的值就更新 max

max ← array[1]
FOR i ← 2 TO n
    IF array[i] > max THEN
        max ← array[i]
    ENDIF
ENDFOR

This pattern — initialise, iterate, compare, update — is the foundation of many algorithms including linear search, counting occurrences, and cumulatively adding elements. Master it thoroughly.

这种”初始化—迭代—比较—更新”的模式是许多算法的基础,包括线性查找、计数统计以及累加求和。务必熟练掌握。


4. Writing Efficient Loops and Conditions | 编写高效的循环与条件

Loops and conditions form the backbone of most algorithms. A well-written WHILE loop requires a properly initialised counter and a carefully designed terminating condition. For counting loops, FOR is almost always preferable because it handles initialisation and increment automatically.

循环和条件语句是大多数算法的骨架。一个编写良好的 WHILE 循环需要正确初始化的计数器以及精心设计的终止条件。对于计数型循环,FOR 循环几乎总是更优的选择,因为它自动处理初始化和步进。

A common pitfall is the infinite loop — a condition that never becomes FALSE. Check every loop to ensure that the terminating condition can actually be reached with the given input. This is particularly important when the input size is zero or one; your loop should handle these boundary cases gracefully.

一个常见的陷阱是无限循环——即终止条件永远不会变为假(FALSE)。请检查每个循环以确认终止条件在给定输入下确实可以达到。当输入规模为 0 或 1 时这一点尤其重要;你的循环应妥善处理这些边界情况。

For conditional statements, remember that ELIF (or ELSE IF) allows multiple mutually exclusive branches. Order the conditions logically — test the most restrictive or uncommon condition first to avoid redundant comparisons.

对于条件语句,请记住 ELIF(或 ELSE IF)允许设置多个互斥的分支。逻辑上应对条件进行排序——优先测试限制性最强或最不常见的条件,以避免冗余比较。

IF mark >= 80 THEN
    grade ← ‘A’
ELIF mark >= 70 THEN
    grade ← ‘B’
ELIF mark >= 60 THEN
    grade ← ‘C’
ELSE
    grade ← ‘D’
ENDIF

Notice how in the above structure, simpler conditions appear earlier. There is no need to specify mark < 80 in the second branch because of the ELIF structure — the previous condition already guarantees it.

注意上述结构中,条件由宽松到严格排列。在第二个分支中无需再写 mark < 80,因为 ELIF 结构已经保证了这一点。


5. Using Standard Algorithm Templates | 使用标准算法模板

There are several ‘classic’ algorithms that appear repeatedly in the CIE specification: linear search, binary search, bubble sort, insertion sort, and the cumulative sum. Knowing these templates by heart gives you an immediate foundation for writing more complex algorithms.

在 CIE 教学大纲中有若干”经典”算法会反复出现:线性查找、二分查找、冒泡排序、插入排序以及累加和。将这些模板牢记于心,就能为编写更复杂的算法提供直接的基础。

For example, linear search is simply a loop that checks each element in turn, stopping when the target is found. The template requires a boolean flag found initially set to FALSE and an index variable i. If the loop ends and found is still FALSE, the item does not exist.

例如,线性查找就是一个依次检查每个元素的循环,当找到目标时停止。该模板需要一个布尔标志 found(初值设为 FALSE)和一个索引变量 i。若循环结束而 found 仍为 FALSE,则说明该项不存在。

found ← FALSE
i ← 1
WHILE found = FALSE AND i <= n
    IF array[i] = target THEN
        found ← TRUE
        position ← i
    ELSE
        i ← i + 1
    ENDIF
ENDWHILE

When modifying such a template, ensure that any additional condition you add does not break the existing structure. For instance, adding a second condition to search for two targets simultaneously requires a fundamentally different approach, not simply inserting another variable into the same loop.

在修改这样的模板时,务必确保新增的条件不破坏现有结构。例如,若要同时搜索两个目标,需要从根本上改变方法,而不能只是简单地在同一循环中增加一个变量。


6. The Art of Modifying Existing Algorithms | 修改现有算法的艺术

Modification questions in CIE exams typically fall into one of three categories: adapting an algorithm to a new data type, adding a new feature, or fixing a logical error. Each requires a different strategy.

CIE 考试中的算法修改题通常分为三类:将算法适配到新的数据类型、增加新功能、或修复逻辑错误。每种类型都需要不同的策略。

To adapt an algorithm, identify every line that depends on the data type and change them consistently. For example, changing a search from integers to strings requires altering the array declaration, the input statement, and the comparison operation — but the loop structure remains identical.

要适配算法,需识别所有依赖于数据类型的代码行并一致地修改它们。例如,将查找算法从整数改为字符串,需要修改数组声明、输入语句以及比较操作——但循环结构保持不变。

To add a new feature, trace the algorithm first to locate the point where the new logic should be inserted. For instance, if a sorting algorithm must additionally count the number of swaps, initialise a counter before the outer loop and increment it inside the swap block.

要增加新功能,请先追踪算法以确定新逻辑应在何处插入。例如,若排序算法需要额外统计交换次数,则在外层循环前初始化一个计数器,并在交换模块内部递增它。

To fix a logical error, use a trace table with the given example input. Compare each expected value with the actual calculated value. The first point where they diverge is where the error lies.

要修复逻辑错误,应使用给定样例输入绘制追踪表。将每一步的期望值与实际计算值进行对比。最先出现偏差的位置就是错误所在。

Original: FOR i ← 1 TO n
Modified: FOR i ← 1 TO n-1  // prevents comparing the last element with a non-existent element

This subtle change — adjusting the boundary of a loop — is the single most common modification required in examination questions. Pay close attention to upper bounds in any loop you write or alter.

“调整循环边界”——这种微妙的修改正是考试题中最常见的考点。无论编写还是修改任何循环,都要格外关注上界。


7. Debugging with Trace Tables | 利用追踪表调试算法

A trace table is a systematic way to record the values of all variables as an algorithm executes line by line. It is the most powerful tool you have for checking the correctness of your own code and for demonstrating to the examiner that the algorithm runs correctly for a given test case.

追踪表是一种系统化记录算法逐行执行时所有变量值的方法。它是检查代码正确性并向阅卷人证明算法在给定测试用例下运行正确的有力工具。

Line i max array[i] Output
1 initialise 5
2 (i=2) 2 5 9
3 update max 2 9 9

When constructing a trace table, include only the variables that change. You do not need to record constants or loop counters that remain unchanged for a given iteration. For nested loops, use one row per execution of the innermost statement.

在构造追踪表时,只需包含发生变化的变量。无需记录常量或某次迭代中保持不变的循环计数器。对于嵌套循环,最内层语句每执行一次就对应一行。

In examination settings, a trace table often carries 4-6 marks. Even if your algorithm is imperfect, a well-drawn trace table shows the examiner exactly where your understanding is strong and can earn you partial credit.

在考试环境中,追踪表通常占 4-6 分。即使你的算法并不完美,一张绘制清晰的追踪表也能向阅卷人展示你的理解深度,并为你赢得步骤分。


8. Handling Boundary and Edge Cases | 处理边界与特殊情形

Consider what happens when a list has zero elements, a single element, or all identical elements. A robust algorithm must handle these cases without crashing. For instance, finding the average of a list with zero elements is a division-by-zero error — the algorithm should check for this separately.

考虑当列表包含零个元素、只有一个元素或全部元素相同时会发生什么。一个健壮的算法必须优雅地处理这些情况。例如,对零元素列表求平均会引发除零错误——算法应单独检查这种情况。

Boundary cases also apply to input validation. If an algorithm expects an integer between 1 and 100, any value outside this range should either be rejected with an error message or clamped to the nearest valid value, depending on the problem’s context.

边界情况同样适用于输入验证。若算法期望输入 1 到 100 之间的整数,则任何超出此范围的值都应被拒绝并显示错误信息,或根据问题背景被钳制到最接近的合法值。

Another common edge case is searching for an item that appears more than once. Decide in advance whether the algorithm should return the first occurrence, the last occurrence, or the total count. Each choice requires different modification of the standard template.

另一个常见的特殊情况是搜索出现多次的目标项。应提前决定算法返回第一个匹配项、最后一个匹配项还是总计数。不同的选择需要对标准模板进行不同的修改。

IF n = 0 THEN
    OUTPUT “Error: Empty list”
ELSE
    sum ← 0
    FOR i ← 1 TO n
        sum ← sum + array[i]
    ENDFOR
    average ← sum / n
ENDIF

Note the IF n = 0 guard at the beginning. This pattern — validate, then process — should be applied in any algorithm that performs calculations on collections of data.

请注意起始处的 IF n = 0 防护检测。这个”先验证、后处理”的模式应应用于任何对数据集合进行计算的算法中。


9. Analysing Time and Space Complexity | 分析时间与空间复杂度

The CIE syllabus requires you to compute the Big-O notation of an algorithm with a single loop, a nested loop, or a sequence of loops. A single loop running n times has a time complexity of O(n); a nested loop where the inner loop also runs up to n times has O(n²).

CIE 教学大纲要求你能够计算包含单层循环、嵌套循环或顺序循环的算法的 Big-O 记号。运行 n 次的单层循环时间复杂度为 O(n);内层也运行 n 次的嵌套循环为 O(n²)。

Binary search has a complexity of O(log n) because it halves the search space each step. A linear search has O(n). This distinction is frequently tested in multiple-choice and short-answer questions.

二分查找的时间复杂度为 O(log n),因为每一步都将搜索空间减半。线性查找为 O(n)。这一区别经常出现在选择题和简答题中。

Space complexity — the amount of memory used — is equally important. An algorithm that copies an array uses O(n) extra space, while an algorithm that swaps elements in-place uses O(1). When asked to modify an algorithm to reduce memory usage, look for temporary arrays that can be eliminated.

空间复杂度——即内存使用量——同样重要。复制数组的算法需要 O(n) 的额外空间,而原地交换元素的算法仅需 O(1)。当要求修改算法以减少内存占用时,寻找可以消除的临时数组即可。

Time complexity of binary search: O(log n)
Time complexity of bubble sort: O(n²)
Time complexity of linear search: O(n)

When writing your answer, always justify the complexity by quoting the structure of the algorithm: ‘Because the loop runs n times, and each iteration does constant work, the complexity is O(n).’

在书写答案时,务必引用算法结构来论证复杂度:”由于循环运行 n 次且每次迭代执行常量工作,因此复杂度为 O(n)。”


10. Examination Techniques for Algorithm Questions | 算法类题目的应试技巧

In the examination, allocate time according to the number of marks. A 6-mark algorithm-writing question should receive approximately 10-12 minutes. Spend the first two minutes planning the structure on rough paper before transcribing the final version.

考试中应依据分值的多少来分配时间。一道 6 分的算法编写题应预留约 10-12 分钟。先用草稿纸花两分钟规划结构,再誊写最终版本。

Always use the pseudo-code convention exactly as specified in the exam paper. If the question says ‘use the standard CIE pseudo-code’, do not invent your own syntax. The examiner will mark your answer against a marking scheme that uses these specific conventions.

务必严格遵循试卷中指定的伪代码约定。若题目说明”使用标准 CIE 伪代码”,切勿自行发明语法。阅卷人将依据使用这些特定约定的标准答案来评分。

For modification questions, clearly state what error you found before presenting the corrected version. Refer to the line number of the original code. For example: ‘Line 7 should compare with < rather than >, because the inner loop must run while the element is larger than the key.’

对于修改题,请先明确说明你发现的错误,再给出修正版本。引用原代码的行号。例如:”第 7 行应使用 < 而非 > 进行比较,因为内层循环必须在元素大于 key 时继续执行。”

Finally, after writing your algorithm, run through the trace table once more to verify correctness. A final check of boundary cases — an empty array, a single element, or the largest possible input — will catch the majority of remaining errors.

最后,在完成算法编写后,再次运行追踪表以验证正确性。对边界情况——空数组、单元素或最大可能的输入——做最后检查即可捕获剩余的大多数错误。


Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading