第二章
1-1
Using figure 2-2 as a model, illustrate the operations of Insertion-Sort on the array A=⟨31,41,59,26,41,58⟩.
以图2-2为模型,说明Insertion-Sort在数组A=⟨31,41,59,26,41,58⟩上的执行情况
1-2
Rewrite the Insertion-Sort procedure to sort into nonincreasing instead of nondecreasing order.
重写Insertion-Sort,使之按非升序排序
for j = 2 to A.length
key = A[j]
i = j - 1
while i > 0 and A[i] < key
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
1-3
Consider the searching problem:
Input: A sequence of n n n numbers A=⟨a1,a2,…,an⟩ and a value ν.
Output: And index i such that ν=A[i] or the special value NIL if ν does not appear in A.
Write the pseudocode for linear search, which scans through the sequence, looking for ν. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.
考虑以下查找问题:
输入:n个数的一个序列A=⟨a1,a2,…,an⟩和一个值v
输出:下标i使得ν=A[i]或者当v不在A中出现时,v为特殊值NIL
写出线性查找的伪代码,他扫描整个序列来查找v。使用一个循环不变式来证明你的算法是正确的。确保你的循环不变式满足三条必要的性质
linear_search(A,v)
for j=1 to A.length
if A[j]==v
return j
return NIL
循环不变式是A[1,j-1]中的所有元素都不同于v
初始化:A[1,j-1]为空,成立
保持:对于接下来的每一步我们都有A[1,j-1]中所有元素不同于v,因为一旦A[j]与v相同,我们就返回j
终止:循环终止条件是j>A.length,因此所以A中的数都比较过了,而v与它们都不同,所以返回NIL
1-4
Consider the problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1)-element array C. State the problem formally and write pseudocode for adding the two integers.
考虑把两个n进制整数加起来的问题,这两个整数分别存储在两个n元数组A和B中。把这两个整数的和应按二进制形式存储在一个(n+1)元数组C中。请给出该问题的形式化描述,并写出伪代码
输入:两个n元二进制数组A<a1,a2…an>,B<b1,b2…bn>
输出:n+1元二进制数组C,C满足C=A+B
add(A, B)
C = new[A.length - 1]
carry = 0
for j = 1 to A.length
C[j] = (A[j] + B[j]) + carry) % 2
carry = (A[j] + B[j]) + carry) / 2
return C
2-1
Express the function n3/1000−100n2−100n+3 in terms of Θ-notation
用Θ记号表示函数n3/1000-100n2-100n+3
Θ(n3)
2-2
Consider sorting n3 numbers in an array A by first finding the smallest element of A and exchanging it with the element in A[1]. Then find the second smallest element of A, and exchange it with A[2]. Continue in this manner for the first n−1 elements of A. Write pseudocode for this algorithm, which is known as selection sort. What loop invariants does this algorithm maintain? Why does it need to run for only the first n−1 elements, rather than for all n elements? Give the best-case and the worst-case running times of selection sort in Θ-notation.
考虑排序存储在数组A中的n个数:首先找出A中的最小元素并将其与A[1]中的元素进行交换。接着,找出A中的次最小元素并将其与A[2]中的元素进行交换。对A中前n-1个元素按该方式继续。该算法称为选择算法,写出其伪代码。该算法维持的循环不变式是什么?为什么它只需要对前n-1个元素,而不是对所有n个元素运行?用Θ记号给出选择排序的最好情况与最坏情况运行时间。
select_sort(A)
for i in 1 to A.length-1
min=i
for j in i+1 to A.length
if A[j]<A[min]
min=j
temp=A[i]
A[i]=A[min]
A[min]=temp
- 循环不变式是A[1,i-1]包含前i-1个最小的元素,且已经排好序
- 为什么是n-1:因为前n-1个数排好序后,最后一个数一定是最大的,所以不用排它了
- 最好情况是(c1+c2+c6+c7+c8)(n-1)+(c3+c4)(n-1+n-2+…+1)=(c1+c2+c6+c7+c8)(n-1)+(c3+c4)(n-1)n/2
最坏情况是(c1+c2+c6+c7+c8)(n-1)+(c3+c4+c5)(n-1)n/2
显然都是Θ(n2