算法导论(CLRS, 2nd) 个人答案 Ch2.1

本文详细解析了非递增插入排序算法的过程,并通过线性搜索算法的实现与证明展示了其正确性。此外,还提供了一个n位数求和的伪代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.1-1:

2011052811321344.png

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;

转载于:https://www.cnblogs.com/flyfy1/archive/2011/05/28/2060607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值