第1章|算法王国的邀请函:欢迎来到编程世界
第 1 章 算法王国的邀请函:欢迎来到编程世界
Chapter 1: An Invitation from the Algorithm Kingdom — Welcome to the World of Programming
你有没有想过这样一个问题:为什么手机知道你想听什么歌?为什么扫地机器人不会撞墙?为什么导航软件总能找到最快的路?这些问题背后,其实都藏着同一个神秘角色——算法(Algorithm)。
> *Have you ever wondered why your phone knows what music you want to listen to? Why a robot vacuum never crashes into walls? Why a navigation app always finds the fastest route? Behind all these questions hides the same mysterious hero — the algorithm.*
在很多人眼里,"算法"这个词听起来像数学家才会用的黑话,像是一道高墙,把门外的小探险家挡在外面。但今天我想告诉你一个秘密:算法的本质,其实非常朴素。它就像一份做蛋糕的食谱——告诉你先放面粉,再打鸡蛋,最后放进烤箱等候。当你按着食谱一步步做下去,香喷喷的蛋糕就会从烤箱里"变"出来。
> *To many people, the word "algorithm" sounds like jargon only mathematicians use, like a tall wall keeping young explorers out. But today I want to share a secret: an algorithm is, at its core, surprisingly simple. It's just like a cake recipe — telling you to add flour first, beat the eggs next, and finally place everything in the oven. When you follow the recipe step by step, a fragrant cake magically "appears" from the oven.*
但问题来了:为什么有的厨师 30 分钟就能做出蛋糕,而有的厨师要花 3 小时?明明食谱都是同一份啊。这个差别,就藏在算法的细节里——步骤的顺序、选择的技巧、资源的分配,这些看不见的"魔法",决定了计算机是快如闪电,还是慢如蜗牛。
> *But here's a question: why can one baker finish a cake in 30 minutes while another needs 3 hours, even with the same recipe? The difference lies in the details of the algorithm — the order of steps, the choice of techniques, the allocation of resources. These invisible "magics" determine whether a computer zips like lightning or crawls like a snail.*
这一章,就是你进入算法王国的第一张入场券。我们会用最贴近生活的方式,把"算法"这个抽象的词变成你厨房里、书包里、游戏里都能用上的工具。
> *This chapter is your first ticket into the Algorithm Kingdom. We'll transform the abstract word "algorithm" into a tool you can use in your kitchen, your backpack, and your games — in the most life-friendly way.*
---
1.1 算法是什么?—— 一份来自厨房的邀请函
1.1 What Is an Algorithm? — An Invitation from the Kitchen
让我们从一个真实的小场景开始。
> *Let's start with a real-life scenario.*
星期六的早晨,妈妈决定教你做一份"蜂蜜小蛋糕"。她从橱柜里拿出一张写满字的小卡片,递给你说:"按照这个做就好啦。"
> *On a Saturday morning, Mom decides to teach you how to make "honey cupcakes." She pulls a small card covered in writing from the cabinet and hands it to you, saying, "Just follow this!"*
卡片上写着:
> *The card reads:*
``` 1. 准备好材料:面粉 200 克、鸡蛋 3 个、蜂蜜 50 克、黄油 100 克 Prepare ingredients: 200g flour, 3 eggs, 50g honey, 100g butter
2. 把黄油放进碗里,用打蛋器打到颜色变浅、像奶油一样 Put the butter in a bowl, beat with a mixer until pale and creamy
3. 加入蜂蜜,继续搅拌 1 分钟 Add honey, keep stirring for 1 minute
4. 分三次加入面粉,每次都用刮刀轻轻拌匀 Add flour in three batches, gently folding with a spatula each time
5. 把面糊倒进小纸杯,每个倒到七分满 Pour the batter into small paper cups, filling each to 70%
6. 烤箱预热到 180°C,把小纸杯放进去 Preheat the oven to 180°C, place the cups inside
7. 烤 20 分钟,表面变成金黄色就完成了 Bake for 20 minutes until the surface turns golden
8. 拿出来放凉 5 分钟,就可以吃啦! Take them out and let cool for 5 minutes. Then enjoy! ```
你照着做了一遍,蛋糕成功了,香喷喷的,妈妈笑了。
> *You followed the steps, succeeded in baking, the cupcakes smelled wonderful, and Mom smiled.*
这就是一个算法。
> *This is an algorithm.*
算法的精确定义 / The Precise Definition of an Algorithm
我们给算法下一个正式的、可以写进教科书里的定义:
> *Here is a formal, textbook-worthy definition of an algorithm:*
> 算法是一组定义明确(definite)、能在有限步骤内完成(finite)、每一步都切实可行(effective)的指令序列,它接收输入(input),产生输出(output)。 > > *An algorithm is a sequence of instructions that is definite (every step is precisely stated), finite (it completes in a limited number of steps), and effective (every step is practically doable). It accepts input and produces output.*
这段定义里有四个关键词:输入、输出、明确的步骤、有限的步骤。我们一个一个来拆。
> *This definition contains four key terms: input, output, definite steps, and finite steps. Let's break them down one by one.*
输入(Input):算法开始之前需要的东西。在蛋糕例子里,输入是面粉、鸡蛋、蜂蜜、黄油。在计算机例子里,输入可能是一组数字、一个问题、或者一段文字。
> *Input: What an algorithm needs before it starts. In the cupcake example, the input is flour, eggs, honey, and butter. In a computer example, the input might be a set of numbers, a question, or some text.*
输出(Output):算法完成之后得到的东西。在蛋糕例子里,输出是香喷喷的小蛋糕。在计算机例子里,输出可能是一个答案、一个排序好的列表、或者一张图片。
> *Output: What an algorithm produces after it finishes. In the cupcake example, the output is the fragrant cupcakes. In a computer example, the output might be an answer, a sorted list, or an image.*
明确的步骤(Definite Steps):每一步都不模糊,任何人在任何时候做,都能得到同样的结果。"打鸡蛋"不明确——打几下?打到什么程度?但是"用打蛋器高速搅拌 30 秒,直到颜色变浅"就非常明确。
> *Definite Steps: Every step is unambiguous — anyone who performs it at any time will get the same result. "Beat an egg" is vague — how many times? To what extent? But "beat with a mixer on high speed for 30 seconds until the color lightens" is very definite.*
有限的步骤(Finite Steps):算法必须在有限步之后停下来。如果一张食谱写着"一直搅拌,直到你觉得够了",那就不是算法,因为它没有一个客观的停止条件。算法必须在某个明确的时刻宣布:"我完成了。"
> *Finite Steps: The algorithm must stop after a limited number of steps. If a recipe says "keep stirring until you feel it's enough," that's not an algorithm, because it has no objective stopping condition. An algorithm must announce at a clear moment: "I'm done."*
把这四个关键词组合起来,你就会发现:算法不一定是计算机的专利。任何带有这四个特征的过程,都是算法。妈妈做蛋糕是算法,你刷牙是算法,过马路是算法,甚至一只蚂蚁从洞穴走到食物再走回来,从某种意义上说,也是一种算法(蚂蚁体内的化学信号就是它的"步骤清单")。
> *Combining these four key terms, you'll find that algorithms aren't necessarily the exclusive domain of computers. Any process with these four features is an algorithm. Mom baking cupcakes is an algorithm; brushing your teeth is an algorithm; crossing the street is an algorithm. Even an ant walking from its nest to food and back is, in some sense, an algorithm (the chemical signals inside the ant serve as its "step list").*
但我们这本书重点关注的,是计算机算法——因为计算机的速度快、记忆力强、不知疲倦,它们能把算法的威力放大无数倍。
> *But what we focus on in this book is computer algorithms — because computers are fast, have strong memory, and never tire, they can amplify the power of algorithms countless times over.*
算法、程序、代码:三个容易混淆的词 / Algorithm, Program, Code: Three Easily Confused Terms
在正式进入算法的细节之前,我们必须先澄清三个常常被混用的词:算法、程序、代码。
> *Before diving into the details of algorithms, we must first clarify three words that are often confused: algorithm, program, and code.*
让我们用一个简单的比喻来区分它们:
> *Let's use a simple analogy to distinguish them:*
``` 算法(Algorithm) → 做蛋糕的食谱(思想、方法) → The recipe for making cupcakes (the idea, the method)
程序(Program) → 一位厨师按照食谱做的全部动作(算法的具体执行) → All the actions a chef performs following the recipe (the concrete execution of the algorithm)
代码(Code) → 厨师写的工作日记(用某种语言记录的程序) → The chef's work diary (the program recorded in some language) ```
更精确地说:
> *More precisely:*
- **算法**是抽象的、与编程语言无关的"做法"。它可以用中文写,可以用英文写,可以用数学符号写,甚至可以用图画写。一个算法可以被翻译成任何编程语言。
> *An algorithm is abstract and independent of any programming language. It can be written in Chinese, English, mathematical symbols, or even pictures. An algorithm can be translated into any programming language.*
- **程序**是算法的**具体实现**。同一个"排序算法",可以写成 Python 程序、Java 程序、C++ 程序……这些不同的程序都是**同一个算法**的不同表达。
> *A program is the concrete implementation of an algorithm. The same "sorting algorithm" can be written as a Python program, a Java program, a C++ program… These different programs are all different expressions of the same algorithm.*
- **代码**是程序的文字形式。代码就是你在屏幕上看到的那些 `print("Hello")`、`for i in range(10)` 之类的字符串。代码是"程序"这个抽象概念的**物质载体**。
> *Code is the textual form of a program. Code is what you see on screen — strings like `print("Hello")` or `for i in range(10)`. Code is the physical carrier of the abstract concept of "program".*
这三者的关系可以用一个简单的图表示:
> *The relationship can be expressed with a simple diagram:*
``` Algorithm (算法: idea) ↓ translated into Program (程序: specific implementation) ↓ written down as Code (代码: characters on screen) ```
举个例子