Algorithm Design (II)

Master trace tables, arrays, and search algorithms

Trace Tables

Learn to trace variable values at every stage of program execution

Data Structures

Understand arrays and strings to solve complex problems

Search Algorithms

Master linear search and optimization techniques

Modularity

Design modular solutions and debug logic errors

算法設計 (二)

掌握追蹤表、陣列和搜索算法

追蹤表

學習在程序執行的每個階段追蹤變量值

數據結構

理解陣列和字串以解決複雜問題

搜索算法

掌握線性搜索和優化技術

模塊化

設計模塊化解決方案並調試邏輯錯誤

Table of Contents 目錄

Trace Tables

Learn to trace algorithm execution step by step

學習逐步追蹤算法執行

Data Structures

Understand arrays and their applications

理解陣列及其應用

Array Basics

Master fundamental array operations

掌握基本陣列操作

Array Operations

Add, delete, and manipulate array elements

添加、刪除和操作陣列元素

Linear Search

Explore sequential search algorithms

探索順序搜索算法

Modularity

Design modular and maintainable code

設計模塊化和可維護的代碼

Trace Tables 追蹤表

What is a Trace Table?

A trace table is a technique used to trace the changes in variables and the states of inputs/outputs when dry running an algorithm. It helps us comprehend an algorithm in depth and spot mistakes.

Why Use Trace Tables?
  • Understand algorithm logic step by step
  • Identify logic errors before running code
  • Track variable values throughout execution
  • Verify algorithm correctness

Trace Table for Sequence

In sequence structures, statements execute one after another in order.

1. x ← 5
2. y ← 10
3. z ← x + y
4. OUTPUT z
Line x y z Output
1 5 - - -
2 5 10 - -
3 5 10 15 -
4 5 10 15 15

Trace Table for Loops

Loops require tracking the loop variable and iterations.

1. sum ← 0
2. FOR i ← 1 TO 3
3. sum ← sum + i
4. ENDFOR
5. OUTPUT sum
Line i sum Output
1 - 0 -
2-3 (1st) 1 1 -
2-3 (2nd) 2 3 -
2-3 (3rd) 3 6 -
5 3 6 6

Trace Table for Selection

Selection structures require tracking which branch executes.

1. score ← 85
2. IF score >= 60 THEN
3. grade ← "Pass"
4. ELSE
5. grade ← "Fail"
6. ENDIF
7. OUTPUT grade
Line score Condition grade Output
1 85 - - -
2 85 TRUE - -
3 85 - "Pass" -
7 85 - "Pass" Pass

什麼是追蹤表?

追蹤表是一種技術,用於在演練算法時追蹤變量的變化和輸入/輸出的狀態。它幫助我們深入理解算法並發現錯誤。

為什麼使用追蹤表?
  • 逐步理解算法邏輯
  • 在運行代碼之前識別邏輯錯誤
  • 追蹤整個執行過程中的變量值
  • 驗證算法正確性

順序結構的追蹤表

在順序結構中,語句按順序一個接一個地執行。

1. x ← 5
2. y ← 10
3. z ← x + y
4. 輸出 z
行號 x y z 輸出
1 5 - - -
2 5 10 - -
3 5 10 15 -
4 5 10 15 15

循環結構的追蹤表

循環需要追蹤循環變量和迭代次數。

1. sum ← 0
2. 對於 i ← 1 到 3
3. sum ← sum + i
4. 結束循環
5. 輸出 sum
行號 i sum 輸出
1 - 0 -
2-3 (第1次) 1 1 -
2-3 (第2次) 2 3 -
2-3 (第3次) 3 6 -
5 3 6 6

選擇結構的追蹤表

選擇結構需要追蹤執行哪個分支。

1. score ← 85
2. 如果 score >= 60 則
3. grade ← "及格"
4. 否則
5. grade ← "不及格"
6. 結束如果
7. 輸出 grade
行號 score 條件 grade 輸出
1 85 - - -
2 85 - -
3 85 - "及格" -
7 85 - "及格" 及格

Interactive Trace Table Generator 互動式追蹤表生成器

Data Structures 數據結構

Introduction to Data Structures

A data structure is a way of organizing and storing data so that it can be accessed and modified efficiently. Arrays are one of the most fundamental data structures in programming.

What is an Array?

An array is a collection of data items of the same type stored in consecutive memory locations. Each item can be accessed using an index number.

Array Terminology
  • Element: Individual data item in the array
  • Index: Position number of an element (starts from 1 in pseudocode)
  • Size: Total number of elements the array can hold
  • Declaration: Creating an array with a specific size

Array vs Individual Variables

Instead of declaring multiple individual variables:

height1 ← 165
height2 ← 172
height3 ← 158
height4 ← 180
height5 ← 169

We can use an array:

DECLARE height[5] : INTEGER
height[1] ← 165
height[2] ← 172
height[3] ← 158
height[4] ← 180
height[5] ← 169
[1]
165
[2]
172
[3]
158
[4]
180
[5]
169

Strings as Character Arrays

A string is formed by a series of characters. Characters in a string can be stored in an array.

word ← "Work Hard!"
[1]
W
[2]
o
[3]
r
[4]
k
[5]
(space)
[6]
H
[7]
a
[8]
r
[9]
d
[10]
!
Important Note

In pseudocode, array indices start from 1. However, in many programming languages like Python and C++, indices start from 0. For example, the first element would be age[0] instead of age[1].

數據結構簡介

數據結構是組織和存儲數據的方式,以便能夠有效地訪問和修改數據。陣列是編程中最基本的數據結構之一。

什麼是陣列?

陣列是相同類型的數據項的集合,存儲在連續的內存位置中。每個項目都可以使用索引號訪問。

陣列術語
  • 元素:陣列中的單個數據項
  • 索引:元素的位置編號(在偽代碼中從1開始)
  • 大小:陣列可以容納的元素總數
  • 聲明:創建具有特定大小的陣列

陣列與單個變量

與其聲明多個單獨的變量:

height1 ← 165
height2 ← 172
height3 ← 158
height4 ← 180
height5 ← 169

我們可以使用陣列:

聲明 height[5] : 整數
height[1] ← 165
height[2] ← 172
height[3] ← 158
height[4] ← 180
height[5] ← 169
[1]
165
[2]
172
[3]
158
[4]
180
[5]
169

字串作為字符陣列

字串由一系列字符組成。字串中的字符可以存儲在陣列中。

word ← "Work Hard!"
[1]
W
[2]
o
[3]
r
[4]
k
[5]
(空格)
[6]
H
[7]
a
[8]
r
[9]
d
[10]
!
重要提示

在偽代碼中,陣列索引從1開始。但是,在許多編程語言如Python和C++中,索引從0開始。例如,第一個元素將是age[0]而不是age[1]。

Basic Array Algorithms 基本陣列算法

Loading Arrays with Data

Loading data into an array using a loop:

DECLARE score[5] : INTEGER
FOR i ← 1 TO 5
INPUT score[i]
ENDFOR

Printing Array Contents

Displaying all elements in an array:

FOR i ← 1 TO 5
OUTPUT score[i]
ENDFOR

Finding Maximum Value

Algorithm to find the largest value in an array:

max ← score[1]
FOR i ← 2 TO 5
IF score[i] > max THEN
max ← score[i]
ENDIF
ENDFOR
OUTPUT "Maximum value:", max

Finding Minimum Value

Algorithm to find the smallest value in an array:

min ← score[1]
FOR i ← 2 TO 5
IF score[i] < min THEN
min ← score[i]
ENDIF
ENDFOR
OUTPUT "Minimum value:", min

Checking if Array is Sorted

Algorithm to check if an array is in ascending order:

sorted ← TRUE
FOR i ← 1 TO 4
IF score[i] > score[i+1] THEN
sorted ← FALSE
ENDIF
ENDFOR
IF sorted = TRUE THEN
OUTPUT "Array is sorted"
ELSE
OUTPUT "Array is not sorted"
ENDIF

將數據載入陣列

使用循環將數據載入陣列:

聲明 score[5] : 整數
對於 i ← 1 到 5
輸入 score[i]
結束循環

打印陣列內容

顯示陣列中的所有元素:

對於 i ← 1 到 5
輸出 score[i]
結束循環

查找最大值

查找陣列中最大值的算法:

max ← score[1]
對於 i ← 2 到 5
如果 score[i] > max 則
max ← score[i]
結束如果
結束循環
輸出 "最大值:", max

查找最小值

查找陣列中最小值的算法:

min ← score[1]
對於 i ← 2 到 5
如果 score[i] < min 則
min ← score[i]
結束如果
結束循環
輸出 "最小值:", min

檢查陣列是否已排序

檢查陣列是否按升序排列的算法:

sorted ← 真
對於 i ← 1 到 4
如果 score[i] > score[i+1] 則
sorted ← 假
結束如果
結束循環
如果 sorted = 真 則
輸出 "陣列已排序"
否則
輸出 "陣列未排序"
結束如果

Array Visualizer 陣列可視化工具

Array Operations 陣列操作

Adding Items to Arrays

To add an item to the end of an array:

// Assuming array has space and count tracks current size
count ← count + 1
array[count] ← newValue

To insert an item at a specific position:

// Insert at position pos, shift elements right
FOR i ← count DOWNTO pos
array[i+1] ← array[i]
ENDFOR
array[pos] ← newValue
count ← count + 1

Deleting Items from Arrays

To delete an item at a specific position:

// Delete at position pos, shift elements left
FOR i ← pos TO count-1
array[i] ← array[i+1]
ENDFOR
count ← count - 1

Flag Variables

A flag variable is a boolean variable used to indicate whether a certain condition has been met. It's commonly used in search algorithms.

found ← FALSE
FOR i ← 1 TO n
IF array[i] = target THEN
found ← TRUE
ENDIF
ENDFOR
IF found = TRUE THEN
OUTPUT "Item found"
ELSE
OUTPUT "Item not found"
ENDIF
Benefits of Flag Variables
  • Track whether a condition has occurred
  • Control program flow based on search results
  • Avoid checking conditions multiple times
  • Make code more readable and maintainable

向陣列添加項目

將項目添加到陣列末尾:

// 假設陣列有空間且count追蹤當前大小
count ← count + 1
array[count] ← newValue

在特定位置插入項目:

// 在位置pos插入,將元素向右移動
對於 i ← count 向下到 pos
array[i+1] ← array[i]
結束循環
array[pos] ← newValue
count ← count + 1

從陣列中刪除項目

刪除特定位置的項目:

// 在位置pos刪除,將元素向左移動
對於 i ← pos 到 count-1
array[i] ← array[i+1]
結束循環
count ← count - 1

標誌變量

標誌變量是一個布爾變量,用於指示是否滿足某個條件。它通常用於搜索算法中。

found ← 假
對於 i ← 1 到 n
如果 array[i] = target 則
found ← 真
結束如果
結束循環
如果 found = 真 則
輸出 "找到項目"
否則
輸出 "未找到項目"
結束如果
標誌變量的好處
  • 追蹤條件是否已發生
  • 根據搜索結果控制程序流程
  • 避免多次檢查條件
  • 使代碼更易讀和可維護

Array Operations Demonstrator 陣列操作演示器

Modularity in Algorithm Design 算法設計中的模塊化

What is Modularity?

Modularity is the practice of breaking down a complex problem into smaller, manageable parts (modules). Each module performs a specific task and can be developed, tested, and maintained independently.

Benefits of Modular Design

  • Easier to understand: Smaller modules are easier to comprehend than one large program
  • Reusability: Modules can be reused in different parts of the program or in other programs
  • Easier debugging: Errors can be isolated to specific modules
  • Team collaboration: Different team members can work on different modules simultaneously
  • Maintainability: Changes can be made to one module without affecting others

Example: Student Grade System

Instead of writing one large algorithm, we can break it into modules:

Module 1: Input Data

Load student scores into array

Module 2: Calculate Average

Find average score of all students

Module 3: Find Highest

Identify student with highest score

Module 4: Generate Report

Output results in formatted report

Logic Error Detection

Modular design helps identify and fix logic errors:

  • Test each module independently with sample data
  • Use trace tables to verify module correctness
  • Check module inputs and outputs match specifications
  • Verify module interactions work as expected
  • Use debugging tools to step through module execution
Best Practices for Modularity
  • Each module should have a single, well-defined purpose
  • Module names should clearly describe their function
  • Minimize dependencies between modules
  • Document module inputs, outputs, and behavior
  • Keep modules small and focused (typically 10-50 lines)

什麼是模塊化?

模塊化是將複雜問題分解為較小、可管理的部分(模塊)的做法。每個模塊執行特定任務,可以獨立開發、測試和維護。

模塊化設計的好處

  • 更容易理解:較小的模塊比一個大程序更容易理解
  • 可重用性:模塊可以在程序的不同部分或其他程序中重用
  • 更容易調試:錯誤可以隔離到特定模塊
  • 團隊協作:不同團隊成員可以同時處理不同模塊
  • 可維護性:可以對一個模塊進行更改而不影響其他模塊

示例:學生成績系統

與其編寫一個大算法,我們可以將其分解為模塊:

模塊1:輸入數據

將學生分數載入陣列

模塊2:計算平均值

查找所有學生的平均分數

模塊3:查找最高分

識別分數最高的學生

模塊4:生成報告

以格式化報告輸出結果

邏輯錯誤檢測

模塊化設計有助於識別和修復邏輯錯誤:

  • 使用樣本數據獨立測試每個模塊
  • 使用追蹤表驗證模塊正確性
  • 檢查模塊輸入和輸出是否符合規範
  • 驗證模塊交互是否按預期工作
  • 使用調試工具逐步執行模塊
模塊化的最佳實踐
  • 每個模塊應該有一個單一、明確定義的目的
  • 模塊名稱應清楚描述其功能
  • 最小化模塊之間的依賴關係
  • 記錄模塊輸入、輸出和行為
  • 保持模塊小而專注(通常10-50行)

Interactive Quiz 互動測驗

Flashcards 閃卡

Click on any card to flip it and see the definition. Test your knowledge of algorithm design concepts!

點擊任何卡片翻轉查看定義。測試您對算法設計概念的了解!

made with 由...製作

Trust & Safety

Report this page