Algorithm Thinking
Develop mindset for 设计 algorithms — 步骤-通过-步骤 recipes 那个解决 problems efficiently and 正确地.
你将学到
- 什么 algorithm 是 and 如何它 differs 从 code
- 如何 设计步骤-通过-步骤解答到 problems
- importance 的 correctness and efficiency
- 常见 algorithm 模式: 搜索, 排序, accumulate
- 如何 验证你的 algorithm 工作之前 coding
概念讲解
Algorithm Thinking
An algorithm is a precise, step-by-step procedure for solving a problem. It is the recipe behind the code — the logic that determines *what* to do, independent of *which language* you write it in. Algorithm thinking is the skill of designing these procedures: breaking a problem into clear, ordered, finite steps that are guaranteed to produce the correct result.
Algorithm vs. Code
An algorithm is an idea; code is an implementation. The algorithm for finding the largest number in a list is: "look at 每个数字, keep track 的 largest 所以远." That algorithm can be implemented in JavaScript, Python, Java, or any language. The algorithm is the same; only the syntax differs. This is why algorithm thinking is a language-independent skill — it transfers everywhere.
Properties of a Good Algorithm
Every algorithm must have these properties:
- Finiteness — it terminates after a finite number of steps. No infinite loops.
- Definiteness — each step is precisely defined. No ambiguity.
- Input — it accepts zero or more inputs.
- Output — it produces at least one output.
- Effectiveness — each step is basic enough to be carried out mechanically.
Common Patterns
Most algorithms you will write fall into a few recognizable patterns:
- Linear search — look at each item one by one until you find the target. Simple but slow for large lists.
- Accumulation — iterate through a collection, building up a running result (sum, count, maximum, concatenation).
- Filtering — iterate and select only items that pass a condition.
- Sorting — arrange items in order (alphabetical, numerical, by a custom key).
- Divide and conquer — split the problem into smaller subproblems, solve each, and combine the results.
Recognizing which pattern fits your problem is the core of algorithm thinking. Once you identify the pattern, the implementation often follows naturally.
Correctness
An algorithm is correct if it produces the right output for every valid input. Verifying correctness means thinking about edge cases: empty inputs, single-element inputs, duplicate values, already-sorted data, reverse-sorted data. A common technique is to trace the algorithm by hand on a small example, writing down the state at each step, and confirming the final output matches the expected result.
Efficiency
Two algorithms can both be correct but differ wildly in speed. Finding a name in an unsorted list by checking each entry takes, on average, N/2 steps. If the list is sorted, binary search takes about log₂(N) steps — for a million entries, that is 20 steps instead of 500,000. Efficiency is the subject of the next lesson (time complexity), but the intuition starts here: always ask "是那里 faster 方式?"
The Design Process
- Understand the problem — what is the input? What is the expected output? What are the constraints?
- Identify the pattern — is this a search, a sort, an accumulation, a transformation?
- Sketch the steps — in pseudocode or a flowchart.
- Trace it by hand — run through a small example to verify.
- Consider edge cases — empty input, single item, duplicates, worst case.
- Implement — translate to code.
- Test — verify with real inputs, including the edge cases.
This process turns "I 有否 idea 哪里到开始" into a systematic approach. The first few steps are thinking, not typing — and that is where most of the value is.
示例代码
// Algorithm: Find the two largest numbers in an array.
// Pattern: Accumulation (track top values while iterating)
// --- Design ---
// Input: array of numbers
// Output: [largest, secondLargest]
// Steps:
// 1. Initialize largest and secondLargest to -Infinity
// 2. For each number in the array:
// a. If number > largest:
// secondLargest = largest
// largest = number
// b. Else if number > secondLargest:
// secondLargest = number
// 3. Return [largest, secondLargest]
function findTopTwo(numbers) {
if (numbers.length < 2) {
throw new Error("Need at least two numbers");
}
let largest = -Infinity;
let secondLargest = -Infinity;
for (const n of numbers) {
if (n > largest) {
secondLargest = largest; // demote current largest
largest = n; // promote new largest
} else if (n > secondLargest) {
secondLargest = n; // update second place only
}
}
return [largest, secondLargest];
}
// Trace: [3, 7, 2, 9, 5]
// n=3: largest=3, second=-Inf
// n=7: largest=7, second=3
// n=2: 2 < 7, 2 > 3? No → no change
// n=9: largest=9, second=7
// n=5: 5 < 9, 5 > 7? No → no change
// Result: [9, 7] ✓
console.log(findTopTwo([3, 7, 2, 9, 5])); // [9, 7]
console.log(findTopTwo([10, 10, 5])); // [10, 10]
这个 algorithm 查找顶部 two 值 in 单个通过 — O(n) 时间. trace in comments 验证 logic 步骤通过步骤. 边缘情况 (fewer than 2 元素) 是 handled 使用 explicit 错误.
动手试一试
- 文本 Sorter
排序是 classic algorithm. Try 不同排序顺序 and think 关于什么 algorithm tool uses internally.
- 行 Deduplicator
移除 duplicates 是 algorithm problem. 这个 tool implements 它 — think 关于如何你 会设计它 你自己.
常见错误
错误写法
开始到 code 之前理解 problem fully.
正确做法
编写下 输入, 输出, and constraints 首先. 如果你 cannot 状态 problem 清晰地 in one sentence, 你做 不理解它 well enough 到解决它. Clarity 的 problem 定义是 half 解答.
错误写法
不 tracing algorithm 通过 hand 之前 coding.
正确做法
选取小 输入 (3-5 项) and walk 通过每个步骤 on paper, 编写下 每个变量's 值. 这个 catches logic 错误 in minutes 相反的 调试 for hours 之后 code 是编写.
错误写法
Ignoring 边缘情况如 空数组 or 单个-元素输入.
正确做法
总是 ask: 什么 happens 使用 0 项? 1 项? 所有 identical 项? Already 排序? Reverse 排序? 这些情况是 哪里正确 algorithms 失败 and buggy ones crash.
相关资源
相关速查表
- JavaScript Cheatsheet
引用 for 循环 and 数组方法 used 到 implement algorithms.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。