Exercise 2.1-1
Using figure 2.4 as a model, illustrate the operations of Insertion-Sort on the array
A=⟨31,41,59,26,41,58⟩ .
插入排序思想:在遍历第二到最后元素过程中,给这个元素挪出正确的位置。
Exercise 2.1-2
Rewrite the Insertion-Sort procedure to sort into nonincreasing instead of nondecreasing order.
非升序排列:
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
Exercise 2.1-3
Consider the searching problem:
Input: A sequence of n numbers
A=⟨a1,a2,…,an⟩ and a valueν .Output: And index
i such thatν=A[i] or the special valueNIL ifν does not appear inA 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.
线性查找伪代码:
SEARCH(A, v):
for i = 1 to A.length
if A[i] == v
return i
return NIL
SEARCH-RECURSIVE(A, size, v) //A[1..size]
if A.size > 0
if A[size] == v
return A.size
return SEARCH-RECURSIVE(A, size-1, v)
return NIL
SEARCH-RECURSIVE 递归式:
循环不变式证明:
查找过程中,
A[1..i−1] 不包含ν ,则继续查找,否则停止查找返回下标。A[1..i−1] 是已经查找过得从位置1 到i−1 的元素,确定不含有ν 。
初始化:
迭代之前,循环不等式成立。因为子数组是空的,没有找到,还要继续。
保持:
如果
终止:
当
Exercise 2.1-4
Consider the problem of adding two n-bit binary integers, stored in two n-element arrays
A andB . The sum of the two integers should be stored in binary form in an(n+1) -element arrayC . State the problem formally and write pseudocode for adding the two integers.
形式化描述:
Input: An array of booleans
Output: An array
伪代码:(pseudocode)
ADD-BINARY(A, B):
C = new integer[A.length + 1]
carry = 0
for i = 1 to A.length
C[i] = (A[i] + B[i] + carry) % 2 // remainder
carry = (A[i] + B[i] + carry) / 2 // quotient
C[i] = carry
return C