Chapter 1: The Role of Algorithms in Computing
1.1 Algorithms
通俗的说,算法就是具有清晰定义的计算过程,输入一组数据,然后生成一组输出数据。算法就是一个计算步骤的序列,将输入转化成输出。
Informally, an algorithm is any well-defined computational procedure that takes some value, or set of values, as input and produces some value, or set of values, as output. An algorithm is thus a sequence of computational steps that transform the input into the output.
输入序列是问题的一个实例
For example, given the input sequence 〈31, 41, 59, 26, 41, 58〉, a sorting algorithm returns as output the sequence 〈26, 31, 41, 41, 58, 59〉. Such an input sequence is called an instance of the sorting problem.
一个算法是正确的,仅当其对所有输入实例,都能停止,并产生正确的输出。
An algorithm is said to be correct if, for every input instance, it halts with the correct output.
Chapter 2: Getting Started
2.1 Insertion sort
插入排序是对少量元素进行排序的有效算法。
《算法艺术与信息学竞赛》算法的渐进复杂度有几个等级。一是多项式算法,它的运行时间随着规模的扩大增长不大,因此叫做有效算法;二是指数级算法O(2^n),它的运行时间增长很快,不是有效算法。还有更大的O(n!),只有在n 很小时才能使用。
We start with insertion sort, which is an efficient algorithm for sorting a small number of elements.
插入排序算法与许多人打扑克时整理手中的牌的方法类似。
Insertion sort works the way many people sort a hand of playing cards.
任何时侯左手的牌都是排好序的。为一张新牌找到正确的位置,我们从右到左比较手中的每一张牌。(停止条件是手中的某张牌比这张牌要小)
At all times, the cards held in the left hand are sorted, and these cards were originally the top cards of the pile on the table.
To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left
INSERTION-SORT(A)
1 for j ← 2 to length[A]
2 do key ← A[j]
3 ▹ Insert A[j] into the sorted sequence A[1 ‥ j - 1].
4 i ← j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] ← A[i]
7 i ← i - 1
8 A[i + 1] ← key
注意:本书中,数组的下标全部从1 开始
// 插入排序是双循环,外层循环从左到右扫描,内层循环从右到左扫描。
INSERTION-SORT(A)
// 外层循环从下标2 到最后一个下标(length[A])
1 for j ← 2 to length[A]
2 do key ← A[j]
3 ▹ Insert A[j] into the sorted sequence A[1 ‥ j - 1].
// 内层循环从外层循环的下标减 1 到 下标1,既1 到1、2 到1、// 3 到1,length[A] – 1 到 1
4 i ← j – 1
//内层循环的停止条件是下标越界或找到一张比key要小的牌,
// 这时A[i+1] 就是要插入的位置。
5 while i > 0 and A[i] > key
// 注意这里把左边每一张比key 大的牌往后挪的操作
// 往后挪一个位置就是这些牌的最终位置
6 do A[i + 1] ← A[i]
7 i ← i – 1
// 现在,A[i+1] 就是key 的最终位置
// 完成了一张牌的插入
8 A[i + 1] ← key