📚 IB CCEA Computer Science: Arrays Key Points | IB CCEA 计算机:数组 考点精讲
Arrays are one of the most fundamental data structures in computer science, enabling the storage and manipulation of multiple values of the same type under a single identifier. In the IB Computer Science course, particularly in the context of algorithmic thinking and programming, a solid grasp of arrays is essential for tackling questions on searching, sorting, abstract data types, and memory management. This revision guide distils the key concepts, common pitfalls, and examination techniques you need to master arrays, with examples drawn directly from typical IB-style pseudocode and problems.
数组是计算机科学中最基础的数据结构之一,能够以单一标识符存储和操作多个同类型的值。在IB计算机科学课程中,尤其是在算法思维和编程环节,扎实掌握数组对于解决搜索、排序、抽象数据类型以及内存管理等问题至关重要。本考点精讲提炼了你需要掌握的核心概念、常见陷阱和考试技巧,并直接结合典型IB风格的伪代码和问题进行解释。
1. Definition and Declaration | 定义与声明
An array is a static data structure that holds a fixed number of elements, all of the same data type, in contiguous memory locations. In IB pseudocode, arrays are declared using the syntax DECLARE ArrayName : ARRAY[LowerBound:UpperBound] OF DataType. The lower bound can be any integer, but very often the IB uses 1‑based indexing in pseudocode (while actual programming languages may use 0‑based indexing).
数组是一种静态数据结构,在连续的内存位置中保存固定数量的元素,且所有元素的数据类型相同。在IB伪代码中,数组的声明语法为DECLARE ArrayName : ARRAY[下限:上限] OF 数据类型。下限可以是任意整数,但IB伪代码常使用1基索引(而实际编程语言可能使用0基索引)。
- Example:
DECLARE scores : ARRAY[1:10] OF INTEGERcreates an array of 10 integers. - 示例:
DECLARE scores : ARRAY[1:10] OF INTEGER创建一个含有10个整数的数组。 - Example:
DECLARE names : ARRAY[0:4] OF STRINGcreates an array of 5 strings, indexed from 0 to 4. - 示例:
DECLARE names : ARRAY[0:4] OF STRING创建一个含有5个字符串的数组,索引从0到4。
You must always ensure that the declared bounds match the intended number of elements, as the array size is fixed at compile time and cannot be changed during execution.
你必须确保声明的上下界与期望的元素个数一致,因为数组的大小在编译时就已经固定,执行期间无法改变。
2. Indexing and Accessing Elements | 索引与元素访问
Each element in an array is accessed via an index. In IB pseudocode, the first element is typically at the lower bound (e.g. 1 or 0). Accessing an element is done by stating the array name followed by the index in square brackets: scores[3]. Reading or writing a value outside the declared bounds causes a run‑time error (often called ‘index out of bounds’).
数组中的每个元素都通过索引访问。在IB伪代码中,第一个元素通常位于下限处(例如1或0)。访问元素的方式是在数组名后加上方括号内的索引:scores[3]。如果读取或写入超出声明边界的值,就会引发运行时错误(通常称为“索引越界”)。
- Valid:
myArray[1] ← 15assigns 15 to the first element. - 有效:
myArray[1] ← 15将15赋给第一个元素。 - Invalid if the array was declared
ARRAY[1:5]:myArray[6] ← 8– this is an out‑of‑bounds error. - 如果数组声明为
ARRAY[1:5],则myArray[6] ← 8无效——这会导致越界错误。
Index calculations in memory are straightforward: the address of arr[i] is base_address + (i – lower_bound) × element_size. IB Higher Level may ask you to compute physical addresses given a base address and element size, so memorise this formula.
内存中的索引计算非常简单:arr[i]的地址为基地址 + (i – 下限) × 元素大小。IB高级水平可能会要求根据给定的基地址和元素大小计算物理地址,因此请牢记此公式。
3. Traversal and Iteration | 遍历与迭代
Traversing an array means visiting each element exactly once, usually with a loop. In IB pseudocode, the most common construct is a FOR...NEXT loop that goes from the lower bound to the upper bound. You can also use WHILE loops, but FOR is safer when the length is known beforehand.
遍历数组意味着恰好访问每个元素一次,通常使用循环实现。在IB伪代码中,最常见的结构是FOR...NEXT循环,从下限循环到上限。你也可以使用WHILE循环,但当长度事先已知时,FOR更为安全。
FOR i ← 1 TO LEN(scores)– assuming 1‑based indexing.FOR i ← 1 TO LEN(scores)– 假设是1基索引。- For 0‑based arrays:
FOR i ← 0 TO LEN(arr)-1. - 对于0基数组:
FOR i ← 0 TO LEN(arr)-1。
A common exam question asks to output the contents of an array, to sum its values, or to find the maximum/minimum. Always initialise your accumulator or extremum variable before the loop and use the correct loop counter range to avoid off‑by‑one errors.
常见的考题要求输出数组的内容、对其求和或寻找最大值/最小值。请务必在循环之前为累加器或极值变量赋初值,并使用正确的循环计数器范围,以免出现差一错误。
4. Initialisation and Filling | 初始化与填充
Arrays can be initialised at the time of declaration or filled later using loops. In pseudocode, you might see: DECLARE vowels : ARRAY[1:5] OF CHAR ← ['a','e','i','o','u']. Alternatively, you can set all elements to a default value: FOR i ← 1 TO 10 DO marks[i] ← 0.
数组可以在声明时初始化,也可以稍后通过循环填充。在伪代码中你可能会看到:DECLARE vowels : ARRAY[1:5] OF CHAR ← ['a','e','i','o','u']。另一种方式是将所有元素设为默认值:FOR i ← 1 TO 10 DO marks[i] ← 0。
Never assume that newly declared arrays contain zero – in pseudocode they are considered uninitialised until you explicitly assign values. In the examination, always show explicit initialisation to avoid losing marks for logic errors.
绝不要假设新声明的数组包含零——在伪代码中,未显式赋值的数组被视为未初始化。在考试中,一定要显示地初始化,以免因逻辑错误而失分。
5. Searching Algorithms with Arrays | 数组的搜索算法
Two main searching techniques feature in the IB syllabus: linear search and binary search. Linear search checks each element from the beginning until the target is found or the end is reached. It works on unsorted data and has O(n) complexity.
IB课程中包含两种主要的搜索技术:线性搜索和二分搜索。线性搜索会从开头检查每个元素,直到找到目标或到达末尾。它适用于未排序的数据,复杂度为O(n)。
Binary search requires the array to be sorted. It repeatedly divides the search interval in half. Compare the target with the middle element; if equal, the search finishes; if smaller, search the left half; if larger, search the right half. The worst‑case complexity is O(log n).
二分搜索要求数组已排序。它反复将搜索区间一分为二。将目标与中间元素比较;若相等则搜索结束;若更小则搜索左半部分;若更大则搜索右半部分。最坏情况复杂度为O(log n)。
- Linear search pseudocode outline:
FOR i ← lower TO upper IF arr[i] = target THEN RETURN i. - 线性搜索伪代码轮廓:
FOR i ← lower TO upper IF arr[i] = target THEN RETURN i。 - Binary search needs
low ← 1,high ← LEN(arr),WHILE low ≤ high,mid ← (low+high) DIV 2. - 二分搜索需要
low ← 1,high ← LEN(arr),WHILE low ≤ high,mid ← (low+high) DIV 2。
Examiners often ask you to trace binary search on a given array or to write the condition that prevents an infinite loop. Ensure your WHILE condition correctly updates low and high.
考官经常要求你针对给定数组追踪二分搜索,或写出防止无限循环的条件。确保你的WHILE条件正确地更新low和high。
6. Sorting Algorithms with Arrays | 数组的排序算法
Sorting is a classic IB topic. The two algorithms you must be able to code, trace and evaluate are bubble sort and selection sort. Both operate directly on the array (in‑place) and have O(n²) average time complexity.
排序是IB的经典主题。你必须能够编码、追踪和评估的两种算法是冒泡排序和选择排序。两者都直接在数组上操作(原地排序),并且平均时间复杂度为O(n²)。
Bubble sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. After each pass, the largest unsorted element ‘bubbles’ to its correct position.
冒泡排序反复遍历列表,比较相邻元素,并在顺序错误时交换它们。每完成一趟,最大的未排序元素都会“冒泡”到其正确的位置。
FOR i ← 1 TO n-1
FOR j ← 1 TO n-i
IF arr[j] > arr[j+1] THEN SWAP arr[j], arr[j+1]
NEXT j
NEXT i
Selection sort divides the array into a sorted and an unsorted region. It repeatedly selects the smallest (or largest) element from the unsorted part and swaps it with the leftmost unsorted element, moving the boundary one step to the right.
选择排序将数组分为已排序和未排序两个区域。它反复从未排序部分选出最小(或最大)元素,并将其与未排序部分最左边的元素交换,然后将边界右移一步。
FOR i ← 1 TO n-1
minIndex ← i
FOR j ← i+1 TO n
IF arr[j] < arr[minIndex] THEN minIndex ← j
NEXT j
SWAP arr[i], arr[minIndex]
NEXT i
You may be asked to count the number of comparisons or swaps, or to describe why one algorithm might be preferred in a given situation (e.g. bubble sort can detect an already sorted list with a flag).
你可能会被要求计算比较或交换的次数,或者描述为什么在特定情境下某种算法更受青睐(例如,冒泡排序可以用标志位检测已排序列表)。
7. Multidimensional Arrays | 多维数组
IB often tests 2‑dimensional arrays (matrices). Declaration: DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER. Access an element with grid[row, column]. Nested loops are needed for traversal: the outer loop typically runs over rows, the inner over columns.
IB经常考查二维数组(矩阵)。声明:DECLARE grid : ARRAY[1:3, 1:3] OF INTEGER。通过grid[row, column]访问元素。遍历需要嵌套循环:外层循环通常遍历行,内层遍历列。
- Row‑major order:
FOR r ← 1 TO 3
FOR c ← 1 TO 3
OUTPUT grid[r,c] - 按行主序:
FOR r ← 1 TO 3
FOR c ← 1 TO 3
OUTPUT grid[r,c]
Be careful with the order of indices: mixing up rows and columns leads to logical errors. In memory, a 2D array is still stored linearly. For an array declared as ARRAY[1:R, 1:C], the address of grid[r,c] in row‑major layout is base + ((r-1)×C + (c-1)) × element_size. HL students should be able to apply this.
注意索引的顺序:行与列混淆会导致逻辑错误。在内存中,二维数组仍然是线性存储的。对于声明为ARRAY[1:R, 1:C]的数组,按行主序布局时grid[r,c]的地址为base + ((r-1)×C + (c-1)) × element_size。HL学生应能运用这一公式。
8. Arrays as Parameters and Return Types | 数组作为形参与返回类型
In IB pseudocode, entire arrays can be passed to procedures or functions. They are normally passed by reference, meaning that changes made inside the sub‑program affect the original array. Use the keyword BYREF to make this explicit: PROCEDURE Update( BYREF arr : ARRAY[] OF INTEGER ).
在IB伪代码中,整个数组可以传递给过程或函数。它们通常以引用方式传递,这意味着子程序内部所作的更改会影响原数组。使用关键词BYREF可明确这一点:PROCEDURE Update( BYREF arr : ARRAY[] OF INTEGER )。
Returning an array from a function is less common in pseudocode but is allowed. You must ensure the function’s return type is declared as an array type. When tracing such code, track whether the original array is being modified or just a local copy.
在伪代码中,从函数返回数组不太常见,但也是允许的。你必须确保函数的返回类型被声明为数组类型。在追踪此类代码时,要注意原数组是被修改了,还是只修改了局部副本。
9. Memory Representation and Efficiency | 内存表示与效率
Arrays occupy contiguous blocks of memory. This allows O(1) direct access to any element, which is the primary advantage. The disadvantage is that the size is fixed; inserting a new element (beyond the declared size) is not possible without creating a new array and copying elements, an O(n) operation.
数组占用连续的内存块。这使得可以O(1)直接访问任何元素,这是它的主要优点。缺点是大小固定;如果不创建新数组并复制元素(O(n)操作),就不可能插入超出声明大小的新元素。
| Operation | Time Complexity |
|---|---|
| Access by index | O(1) |
| Linear search | O(n) |
| Binary search (sorted) | O(log n) |
| Insert/delete at end* | n/a (static size) |
| Insert/delete in middle | O(n) (requires shifting) |
*For static arrays, appending beyond capacity is not supported. Dynamic arrays (like those in Python) are not typically part of the core IB pseudocode, though they may appear in option topics.
*对于静态数组,不支持在容量外追加。动态数组(如Python中的列表)通常不属于IB核心伪代码的一部分,尽管它们可能出现在选项主题中。
10. Common Pitfalls and Exam Tips | 常见陷阱与应试技巧
- Off‑by‑one errors: Failing to align loop bounds with array indexing. Always double‑check the declared range and use
LEN()carefully. - 差一错误:未能将循环边界与数组索引对齐。请始终检查声明的范围并谨慎使用
LEN()。 - Uninitialised elements: Forgetting to initialise leads to undefined behaviour. Explicitly set every element before use.
- 未初始化元素:忘记初始化会导致未定义行为。在使用前显式地为每个元素赋值。
- Modifying the array while iterating: If you add or remove elements inside a loop, indices can shift unexpectedly. For static arrays, this is not an issue, but be careful in higher-level options dealing with collections.
- 在迭代时修改数组:如果在循环内部添加或删除元素,索引可能意外偏移。对于静态数组这不是问题,但在涉及集合的高阶选项中要小心。
- Confusing row and column in 2D arrays: Adopt a consistent mental model (row‑major) and test with small matrices.
- 在二维数组中混淆行列:采用一致的思维模型(行主序),并用小矩阵进行测试。
- Incorrect stopping condition for binary search: Using
low < highinstead oflow ≤ highcan miss the element when low equals high. - 二分搜索的停止条件不正确:使用
low < high而非low ≤ high可能会在low等于high时错过元素。 - Swapping without a temporary variable: In pseudocode, always show the three‑step swap:
temp ← a; a ← b; b ← temp. Some languages allow parallel assignment, but clarity is safer. - 交换时不使用临时变量:在伪代码中,始终展示三步交换:
temp ← a; a ← b; b ← temp。有些语言支持并行赋值,但清晰起见更为稳妥。
In the exam, trace tables are your best friend. When asked to trace an algorithm, set up a table with columns for each variable and the array state. Update step by step – this will catch most logical mistakes and earn you method marks even if the final answer is slightly off.
在考试中,追踪表是你最好的朋友。当要求追踪算法时,建立一个包含每个变量和数组状态列的表格。一步一步更新——这样能发现大多数逻辑错误,并且即使最终答案稍有偏差,也能为你挣得过程分。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导