2.1-1:

2.1-2:

NON-INCREASING-INSERTION-SORT(A)

  for j: 1~ length(A)-1:

    if(A[j] < A[j-1]):

    key = A[j]; t = j-1;

    while(A[t] < key && t>=0):

      A[t+1] = A[t];

      t--;

    A[t] = key;

  return A;

 

 

2.1-3:

// Assumption: If there're duplicated elements, only return

//    the index of the first element.

LINEAR-SEARCH(A, key)

  for i: 0~ length(A)-1:

  if(A[i] == key)  return i;

  return NIL;

Proof:

loop invariant: all the elements has been searched doesn't equal to "key"

Initialization: At the start of each iteration, no element has been searched,

  loop invariant holds.

Maintenance: if there's element equal to the "key", it would terminate

  immediately; therefore as long as the algorithm is on going, it would hold the loop invariant.

Termination: if the algorithm runs until the end of the loop, didn't

  terminate, it means no element equal to the "key".

  Therefore the algorithm is correct.

2.1-4:

Input: Given two n-bit integers, stored in n-element arrays A and B (the lower index stores the least   significant bit), where each element only stores 0 or 1.

Output: An array C of (n+1) elements stores the sum of that two n-bit number

Pseudocode:

N-BIT-NUMBER-SUM(A,B)

  // initialization

  carry = 0;

  for i: 0 ~ length(A) -1:

  C[i] = carry;

  carry = A[i] & C[i];

  C[i] ^= A[i];

  carry |= B[i];

  C[i] ^= B[i];

  C[i] = carry;  // here i = length(A)

  return C;