跳到主要内容

数据结构与算法

大学计算机科学知识点 5

本主题的视频课程 打开视频页面
7:45

数据结构与算法

这门课讲的是如何根据开销选择容器。第一个单元介绍衡量标准:开销如何随输入规模增长。接下来的四个单元介绍容器:列表、栈和队列、哈希表、树和堆,以及图。最后两个单元介绍算法:排序和搜索。这里所有关于开销的结论,都是在讲义中列出的数据集上统计得出的。

英文讲解 · 可切换中英文字幕

探索

Growth classes pull apart

Move n and compare log n, n, n log n and n² operation counts. Even at n = 16 the quadratic is sixteen times the linear, and the gap keeps widening.

探索

Last in, first out

Step through push 3, push 7, push 1, then two pops. The pops return 1 then 7, and 3 stays at the bottom.

探索

Search costs the height

Insert 50, 30, 70, 20, 40, 60, 80 to get a perfect tree of height 2, then search for 40. The path visits 50, 30, 40, three comparisons for seven nodes.

探索

Four probes for 43

On the sorted 16-slot array 3, 7, …, 63, binary search for 43 probes indices 7, 11, 9 and 10. Switch to linear search and count how many more comparisons it needs.

讲义

English

What this course is, and how to use it

This is the fifth course in University Computer Science: data structures and algorithms 数据结构与算法. It covers the containers a program uses to hold data and the step-by-step methods that work through them, and how to choose between them by what they cost.

A limit, stated once: this is a study course, not a degree. Python 3 is the language used, and every fragment is original. Every cost claim in this handout was checked by counting operations on the exact data printed here.

  • Unit 5.1 is the measuring tool: how cost grows.
  • Units 5.2–5.5 are the containers: lists, hash tables, trees and graphs.
  • Units 5.6–5.7 are the methods: sorting and searching.

The habit to build: never trust a cost claim you have not counted. Each unit fixes one set of data, and you can count every number again yourself.

Asymptotic analysis

Why it matters. Choosing between two solutions means choosing between their growth rates. At $n = 1000$, the difference between $n \log n$ and $n^2$ is a factor of about $100$.

The idea.

  • Big-O 大O记号 is an upper bound, up to a constant: $f(n) = O(g(n))$ when $f(n) \le c\,g(n)$ for all large $n$.
  • Big-Ω is the matching lower bound.
  • Big-Θ 大Θ记号 gives the exact growth rate.

Drop the constants and the smaller terms: $3n^2 + 5n + 7$ is $\Theta(n^2)$, because the $n^2$ term grows much faster than the rest.

$n$ $\log_2 n$ $n$ $n\log_2 n$ $n^2$ $2^n$
10 3 10 33 100 1 024
100 7 100 664 10 000 $\approx 10^{30}$
1000 10 1000 9 966 $10^6$ $\approx 10^{301}$
Complexity curves
Growth of the common classes over one axis: logarithmic stays flat, exponential leaves the page

Why halving gives log n. An algorithm that halves what is left at every step needs $\log_2 n$ steps. Binary search on $n = 16$ items makes at most $4$ halvings, because $2^4 = 16$. And $\log_2$ of a million is only about $20$: this flat growth is why log-time algorithms feel instant.

Worked example 1: counting is better than guessing. Take two loops over the same array of $n = 100$ items.

  • A single loop runs its body $100$ times.
  • A nested loop runs its body $100 \times 100 = 10\,000$ times.

Double $n$ to $200$. The single loop doubles to $200$; the nested loop grows four times, to $40\,000$. The measured ratio $4 = 2^2$ gives the power of $n$, read straight from the data.

Worked example 2: reading the class from code.

  • A loop that halves i = i // 2 each time: $\Theta(\log n)$ steps.
  • Two loops over $n$, one after the other: the costs add, $\Theta(n) + \Theta(n) = \Theta(n)$.
  • A loop over $n$ inside a halving loop: the costs multiply, $\Theta(n \log n)$. This is the shape of merge sort.

Common mistakes.

  • Reading Big-O as a promise about speed. Constants matter when $n$ is small.
  • Forgetting how the data is stored. $O(1)$ indexing is true for arrays, not for linked lists.
  • Giving the best case when the question asks for the worst case.

Summary. O bounds from above, Ω from below, and Θ gives the exact rate. Drop constants and smaller terms. Measure by doubling $n$ and read off the power.

Lists, stacks and queues

Why it matters. Linear structures are the default containers. Their costs differ at the two ends, and knowing which end is cheap is most of this topic.

A very long line of people waiting one behind another, stretching along a wall into the distance
A line of people is a queue you can see. You join at the back and are served from the front, so whoever waited longest is served first — that is exactly FIFO
A tall pile of books stacked flat on top of one another
A pile of books is a stack you can see. You can only add or take a book from the top, so the last one you put on is the first one you take off — that is exactly LIFO
A stack drawn as a container with A at the bottom, B and C above; push and pop both act at the top. A queue drawn as a row A, B, C; enqueue adds at the rear on the right and dequeue removes from the front on the left
Stack: one end does everything. Queue: add at the rear, remove from the front

The idea.

structure how it works cheap expensive
array 数组 (a Python list) one block of memory index $i$: $O(1)$; add at the end insert at the front: $O(n)$
linked list 链表 each node 节点 points to the next insert after a node you have found: $O(1)$ find by index: $O(n)$
stack 栈 add and remove at one end (LIFO) push, pop: $O(1)$
queue 队列 add at one end, remove at the other (FIFO) enqueue, dequeue: $O(1)$
Array and linked layouts
One contiguous block with computed addresses versus nodes chained by pointers; the stack and queue differ only in which ends they use

Why adding at the end is O(1) on average. When the array is full, it grows to twice its size and copies everything across. Over $n$ appends, the total number of copies is at most about $2n$, so the average append costs a constant amount, even though one append now and then copies $n$ items. This is called amortised cost. Inserting at position $0$ never averages out like this: every insert moves all $n$ items, so $n$ front inserts move $\Theta(n^2)$ items in total (measured: the count grows four times when $n$ doubles).

Worked example 1: a stack trace. push 3, push 7, push 1, then pop, pop: the pops return $1$, then $7$. Last in, first out. A classic use is checking brackets. Scan ([]){}, pushing every opening bracket; each closing bracket must match the top of the stack. This string is balanced. In ([)], the ) finds [ on top, so it fails.

Worked example 2: a queue trace. Enqueue a, b, c. Two dequeues return a, then b, and the front is now c. First in, first out. Two stacks can act as a queue (an inbox and an outbox; each item is moved twice). In Python, collections.deque, a double-ended list, handles both ends in $O(1)$.

Common mistakes.

  • Using list.pop(0) in a loop. Each call is $O(n)$; use deque.popleft().
  • Looking up a linked list by index. You must walk the chain: $O(n)$.
  • Thinking a Python list is linked. It is an array.

Summary. Array: $O(1)$ index, $O(n)$ insert at the front. Linked list: $O(1)$ insert after a node you have found. A stack uses one end; a queue uses two. A deque handles both ends in $O(1)$.

Hashing

Why it matters. A hash table answers "is this key here?" in one step on average. It is the engine inside sets, dictionaries and caches.

Resolving a collision where keys A and B both hash to slot 2. Linear probing puts B in the next free slot (3); chaining keeps slot 2 pointing to a linked list of A then B
Resolving a hash collision: linear probing uses the next free slot; chaining keeps a linked list per slot

The idea. A hash function 哈希函数 turns a key into a bucket number. With $h(k) = k \bmod 13$, the keys $4, 17, 30, 43$ all go to bucket $4$. This is a collision 冲突. There are two ways to handle it:

  • chaining 链地址法: each bucket holds a list of its keys;
  • open addressing 开放寻址法: probe slots until a free slot is found. With linear probing, $17 \to 5$, $30 \to 6$ and $43 \to 7$.
Hash buckets
Thirteen buckets under h(k) = k mod 13: keys 4, 17, 30, 43 chain in bucket 4 and 12, 25, 38 chain in bucket 12

Why the load factor decides the cost. With $m$ buckets and $n$ keys, the load factor 负载因子 is $\alpha = n/m$. It is also the average chain length. Our fixed keys $[4, 17, 30, 43, 12, 25, 38]$ give $\alpha = 7/13 \approx 0.54$: bucket $4$ holds $4$ keys, bucket $12$ holds $3$, and eleven buckets are empty. With chaining, a successful search takes about $1 + \alpha/2$ comparisons. If $m$ grows as $n$ grows, the expected cost stays $O(1)$. This resizing is why dictionaries stay fast.

Worked example 1: exact chains. Insert $4, 17, 30, 43$ with $h(k) = k \bmod 13$. Every key goes to bucket $4$, so the chain reads $4 \to 17 \to 30 \to 43$. Searching for $43$ checks $4, 17, 30, 43$: four comparisons. This is the worst case for these keys, and a good hash function avoids it on average.

Worked example 2: probing the same keys. Open addressing with linear probing:

key slots tried probes
4 4 1
17 4, 5 2
30 4, 5, 6 3
43 4, 5, 6, 7 4

That is $1 + 2 + 3 + 4 = 10$ probes for four inserts. Full slots gather into long runs (clustering 聚集). This is why real tables keep $\alpha$ below about $0.75$, and why the probing order matters.

Common mistakes.

  • Using a power of two for $m$ when many keys share the same low bits. Choose a prime.
  • Changing a key while it is in the table: its hash, and so its bucket, changes.
  • Expecting $O(1)$ in the worst case. That needs a perfect hash, or a tree in each bucket.

Summary. A hash spreads keys over buckets. Collisions are normal, so choose how to handle them (chain or probe). $\alpha = n/m$ predicts the cost; resize to keep it constant.

Trees and heaps

Why it matters. Trees get logarithmic costs by halving the remaining work at each level. Search and insert in a balanced BST cost $O(\log n)$. Heap insertion costs $O(\log n)$, and reading the smallest or largest item at the root costs $O(1)$.

A binary search tree with root 50; 30 left and 70 right of it; 20 and 40 below 30; 60 and 80 below 70; 35 to the left of 40. The leaves are 20, 35, 60 and 80
Built by inserting 50, 30, 70, 20, 40, 60, 80, 35 in that order

The idea.

  • A binary search tree 二叉搜索树 keeps one rule at every node: left subtree $<$ node $<$ right subtree. Inserting $50, 30, 70, 20, 40, 60, 80$ builds a perfect tree of height $2$. An inorder walk (left, node, right) reads $20, 30, 40, 50, 60, 70, 80$: sorted, because of the rule.
  • A heap 堆 is a complete tree stored in an array. The children of index $i$ are at $2i+1$ and $2i+2$. A min-heap 小顶堆 keeps every parent $\le$ its children, so the smallest item is at index $0$.
Tree and heap diagrams
Left: the BST built by inserting 50, 30, 70, 20, 40, 60, 80. Right: the min-heap array [1, 3, 8, 5] drawn as its implicit tree with index labels

Why the height is the cost. A perfect tree of height $h$ holds $2^{h+1} - 1$ nodes: $7$ for $h = 2$, $15$ for $h = 3$, $31$ for $h = 4$. A complete binary tree with $n$ nodes has height $\lfloor \log_2 n \rfloor$, while a balanced BST has height $O(\log n)$, and every walk from the root to a leaf (search, insert, sift) costs that height. An unbalanced tree loses this: inserting the sorted keys $1, 2, 3, 4$ gives a chain of height $3 = n - 1$, so search becomes $O(n)$. This is why balanced trees (AVL, red-black) rotate nodes to stay logarithmic.

Worked example 1: search and insert in a BST. Search for $40$:

  1. $40 < 50$: go left to $30$.
  2. $40 > 30$: go right to $40$.
  3. Found, after $3$ comparisons among $7$ nodes: one per level.

Insert $35$: follow the same path and attach it to the left of $40$. The inorder walk now reads $20, 30, 35, 40, 50, 60, 70, 80$, still sorted.

Worked example 2: sifting up in a heap. Build a min-heap by inserting $5, 3, 8, 1$:

  1. $5$ goes to index $0$.
  2. $3$ goes to index $1$, is smaller than its parent $5$, and swaps with it: $[3, 5]$.
  3. $8$ goes to index $2$ and stays: $[3, 5, 8]$.
  4. $1$ goes to index $3$, swaps with its parent $5$, then with $3$: $[1, 3, 8, 5]$.

Check that every parent $\le$ its children: $1 \le 3$ and $1 \le 8$; $3 \le 5$. heapq.heapify builds a heap from a whole array in $O(n)$ by sifting down, starting from the middle.

Common mistakes.

  • Forgetting that a heap is only partly ordered. An inorder walk of $[1, 3, 8, 5]$ means nothing; only the root is special.
  • Expecting a BST to stay balanced by luck when the input is sorted.
  • Mixing 1-based child formulas ($2i$, $2i+1$) with a 0-based array ($2i+1$, $2i+2$).

Summary. BST: the order rule; inorder walk = sorted; cost = height, which is $\log n$ when balanced. Heap: a complete tree in an array; each parent beats its children; the root is the minimum, read in $O(1)$; a sift costs the height.

Graphs and traversal

Why it matters. Every network is a graph: roads, course prerequisites, friends of friends. The two ways of walking a graph answer the questions "can I get there?", "how many steps away?" and "what is its structure?".

The idea. A graph is $G = (V, E)$. Our fixed course graph has $V = \{A \ldots H\}$ ($8$ nodes) and $10$ undirected edges: $AB, AC, BD, CD, CE, DF, EF, EG, FH, GH$.

  • An adjacency list 邻接表 stores the neighbours of each node: $20$ entries for $10$ undirected edges (each edge appears twice).
  • An adjacency matrix 邻接矩阵 is an $8 \times 8$ grid of $64$ cells, with a $1$ for each edge.
Graph with traversal order
The course graph: breadth-first from A visits in the numbered order A, B, C, D, E, F, G, H — layer by layer

Why a traversal costs O(V+E). Breadth-first search (BFS) and depth-first search (DFS) mark each node once ($V$ work) and look at each stored edge once ($E$ work): $O(V + E)$, here $8 + 10$. With a matrix, the cost is $O(V^2)$, because each row checks all $8$ columns, edge or not. So the list wins on sparse graphs ($E$ much smaller than $V^2$), and the matrix wins when the graph is dense or you only need to check one cell.

Worked example 1: BFS by layers. Start at $A$ and visit neighbours in alphabetical order:

layer nodes
0 $A$
1 $B, C$
2 $D, E$
3 $F, G$
4 $H$

The order is $A, B, C, D, E, F, G, H$. A node's layer is its shortest distance from $A$ in edges. This is what the queue gives you: nodes leave in the order they arrived.

Worked example 2: DFS with a stack. Start at $A$ and take neighbours in alphabetical order:

  1. $A \to B \to D$.
  2. The next unvisited neighbour of $D$ is $C$; then $C \to E$.
  3. $E \to F$, then $F \to H$.
  4. The unvisited neighbour of $H$ is $G$, which ends the walk.

The order is $A, B, D, C, E, F, H, G$: one deep walk that goes back at dead ends. The graph and the $O(V+E)$ cost are the same, but the shape is different. BFS finds the fewest steps; DFS shows paths and cycles.

Common mistakes.

  • Forgetting to mark nodes as visited. Any cycle then causes an endless loop.
  • Treating the BFS layer as a weighted distance. It counts edges only; weighted graphs need Dijkstra's algorithm.
  • Setting only one cell for an undirected edge in a matrix. Both $[u][v]$ and $[v][u]$ must be set.

Summary. Use a list for sparse graphs and a matrix for dense ones. Both traversals are $O(V+E)$. The queue gives layers and the fewest steps; the stack gives deep paths.

Sorting

Why it matters. Sorting comes before binary search, removing duplicates and merging. It is also the classic lesson in cost analysis: the same task, with very different costs.

Rows tracing an insertion sort of D, T, H, R across three passes; the sorted prefix is shaded and arrows show each larger element shifting right to let the key drop in
An insertion sort of [D, T, H, R], shifting each key into its place pass by pass

The idea. The course data is $[5, 2, 9, 1, 7, 3]$.

  • Insertion sort 插入排序 grows a sorted part at the front, moving each new item back into place. After the pass for $1$, the sorted part reads $1, 2, 5, 9$.
  • Merge sort 归并排序 splits the list in half, sorts each half, and merges the two.
  • Quicksort splits the list around a pivot value.
  • Bubble sort swaps neighbours that are out of order. It is useful for teaching but rarely used.
Insertion-sort snapshots
Insertion sort on the course dataset: each row is one insertion; the shaded prefix is already sorted

Counting inversions. An inversion 逆序 is a pair of items in the wrong order. The course data has eight:

$$(5,2),\ (5,1),\ (5,3),\ (2,1),\ (9,1),\ (9,7),\ (9,3),\ (7,3)$$

Each swap of two neighbours fixes exactly one inversion. So any sort that only swaps neighbours makes exactly $8$ swaps here, and insertion sort makes exactly $8$ shifts. Merge sort moves each item through only about $\log_2 n$ levels of merging, and one merge step can fix many inversions at once. That is why $O(n \log n)$ beats $O(n^2)$.

Worked example 1: insertion sort by hand. $[5, 2, 9, 1, 7, 3]$:

insert shifts sorted part after
2 1 $2, 5$
9 0 $2, 5, 9$
1 3 $1, 2, 5, 9$
7 1 $1, 2, 5, 7, 9$
3 3 $1, 2, 3, 5, 7, 9$

Total shifts: $1 + 0 + 3 + 1 + 3 = 8$, exactly the number of inversions. The comparisons total $11$: one for each shift, plus one that stops the pass for each item that does not reach the front ($9$, $7$ and $3$).

Worked example 2: merge sort on the same data. Split into $[5, 2, 9]$ and $[1, 7, 3]$. Sorting each half gives $[2, 5, 9]$ and $[1, 3, 7]$, and merging gives $1, 2, 3, 5, 7, 9$. The measured number of comparisons is $10$ for this input, against $11$ for insertion sort. That is close here, but the two families grow apart quickly: at $n = 1000$, $n \log_2 n \approx 9\,966$ against $n^2 = 10^6$, a factor of about $100$.

Common mistakes.

  • Thinking quicksort's worst case is rare. With the first item as the pivot, already sorted input is exactly the worst case, $O(n^2)$.
  • Expecting heapsort to be stable. It is not; merge sort is.
  • Counting only comparisons when moving large records costs more.

Summary. Sorts that swap neighbours pay one move per inversion ($\Theta(n^2)$ in the worst case). Merge sort takes $\Theta(n \log n)$; quicksort takes $\Theta(n^2)$ in the worst case. Merge sort and insertion sort are stable; quicksort and heapsort are not.

Searching

Why it matters. Looking things up is one of the most frequent operations in real programs. On a page of data, it is the difference between $16$ checks (linear) and $4$ (binary).

An open telephone directory
Searching a sorted list, like a phone book, is far faster than checking every entry one by one
Binary search for 23 in the sorted list 2, 5, 8, 12, 16, 23, 38, 56, 72 with indexes 0 to 8. Probe 1 at index 4 finds 16, less than 23, so go right; probe 2 at index 6 finds 38, greater than 23, so go left; probe 3 finds 23 at index 5. Discarded items are greyed
Each probe discards half of what remains

The idea.

  • Linear search 线性查找 checks the items one by one: $O(n)$, and the data need not be sorted.
  • Binary search 二分查找 works on a sorted range: check the middle and keep one half.

Our sorted array has $16$ items, at indices $0$–$15$:

$$[3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63]$$

Searching for $43$ checks indices $7, 11, 9, 10$ (values $31$, $47$, $39$, $43$): four probes, found.

Binary-search probes
The 16-slot sorted array with the probe trail for 43: mid at 7 (too small), 11 (too big), 9 (too small), 10 — found in 4 probes

The limit on probes. Each probe halves the number of items left. After $k$ probes, at most $\lceil n / 2^k \rceil$ remain, so the worst case is $\lceil \log_2(n+1) \rceil$ probes. For $n = 16$ that is $5$ (our search for $43$ took $4$). Linear search pays up to $16$ for each query, and $16$ for every miss; binary search pays at most $5$ every time. The condition is that the data is sorted. On unsorted data the halving argument fails, and only linear search gives correct answers.

Worked example 1: the probe trail. Searching for $43$:

lo hi mid value next
0 15 7 31 $31 < 43$, so lo = 8
8 15 11 47 $47 > 43$, so hi = 10
8 10 9 39 $39 < 43$, so lo = 10
10 10 10 43 found

Found at index $10$ after $4$ probes. For comparison, linear search checks $11$ values to reach index $10$.

Worked example 2: a miss that reaches the limit. Search for $64$, which is not there (it is larger than every item). Binary search probes index $7$ ($31$), $11$ ($47$), $13$ ($55$), $14$ ($59$) and $15$ ($63$): five probes. Then the range is empty, and it reports "not found". Linear search checks all $16$ before giving the same answer. A miss costs binary search its worst case and linear search the whole array, and the gap keeps growing, as $\log n$ against $n$.

Common mistakes.

  • Binary search on unsorted data. It gives wrong answers silently; it does not crash.
  • An off-by-one error in the update. lo = mid instead of lo = mid + 1 can loop for ever.
  • Computing the middle as $(lo + hi) / 2$ in languages where integers can overflow. lo + (hi - lo) // 2 is safe.

Summary. Linear search: no condition on the data, $O(n)$. Binary search: the data must be sorted; at most $\lceil \log_2(n+1) \rceil$ probes, so $16$ items need at most $5$.

词汇
English 中文 拼音
data structures and algorithms/ˈdeɪtə ˈstrʌktʃəz ænd ˈælɡərɪθəmz/ 数据结构与算法 shù jù jié gòu yǔ suàn fǎ
Big-O/bɪɡ əʊ/ 大O记号 dà O jì hào
Big-Θ 大Θ记号 dà Θ jì hào
array/əˈreɪ/ 数组 shù zǔ
linked list/lɪŋkt lɪst/ 链表 liàn biǎo
node/nəʊd/ 节点 jié diǎn
stack/stæk/ 栈 zhàn
queue/kjuː/ 队列 duì liè
hash function/hæʃ ˈfʌŋkʃn/ 哈希函数 hā xī hán shù
collision/kəˈlɪʒn/ 冲突 chōng tū
chaining/ˈtʃeɪnɪŋ/ 链地址法 liàn dì zhǐ fǎ
open addressing/ˈəʊpən əˈdresɪŋ/ 开放寻址法 kāi fàng xún zhǐ fǎ
load factor/ləʊd ˈfæktə/ 负载因子 fù zài yīn zǐ
clustering/ˈklʌstərɪŋ/ 聚集 jù jí
binary search tree/ˈbaɪnəri sɜːtʃ triː/ 二叉搜索树 èr chā sōu suǒ shù
heap/hiːp/ 堆 duī
min-heap/mɪn hiːp/ 小顶堆 xiǎo dǐng duī
adjacency list/əˈdʒeɪsənsi lɪst/ 邻接表 lín jiē biǎo
adjacency matrix/əˈdʒeɪsənsi ˈmeɪtrɪks/ 邻接矩阵 lín jiē jǔ zhèn
inversion/ɪnˈvɜːʃn/ 逆序 nì xù
insertion sort/ɪnˈsɜːʃn sɔːt/ 插入排序 chā rù pái xù
merge sort/mɜːdʒ sɔːt/ 归并排序 guī bìng pái xù
linear search/ˈlɪnɪə sɜːtʃ/ 线性查找 xiàn xìng chá zhǎo
binary search/ˈbaɪnəri sɜːtʃ/ 二分查找 èr fēn chá zhǎo

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

IGCSE, A-Level & AP