Chapter 2 Getting Started 2.1 Insertion sort

Chapter 2 Getting Started

2.1 Insertion sort

insertion sort is an efficient algorithm for sorting a small number of elements.

  • The pseudocode
INSERTION-SORT(A)
1 for j = 2 to A.length
2     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[j] > key
6     		A[i+1] = A[i]
7    		i = i - 1
8     A[i+1] = key
  • Loop invariants
  1. Initialization: It is true prior to the first iteration of the loop.
  2. Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration.
  3. Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
  • Exercises
  • 2.1-2
    Rewrite the INSERTION-SORT procedure to sort into nonincreasing instead of nondecreasing order.

C:

for(i=1;i<n;i++)
	{
		key=a[i];
		j=i-1;
		while(j>=0&&key>a[j])
		{
			a[j+1]=a[j];
			j--;
		}
		a[j+1]=key;
	}
  • 2.1-3
    Input: A sequence of 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 pseudocode for linear search, which scans through the sequence, looking for v. Using a loop invariant, prove that your algorithm is correct. Make sure that your loop invariant fulfills the three necessary properties.

The pseudocode just looks like this :

SEARCH(A, v):
  for i = 1 to A.length
      if A[i] == v
          return i
  return NIL

I’m going to state the loop invariant as:

At the start of each iteration of the for loop, the subarray A[1..i−1] consists of elements that are different than ν.

Here are the three properties:

  • Initialization
    Initially the subarray is the empty array, so proving it is trivial.

  • Maintenance
    On each step, we know that A[1…i−1] does not contain ν. We compare it with A[i]. If they are the same, we return i, which is a correct result. Otherwise, we continue to the next step. We have already insured that A[A…i−1] does not contain ν and that A[i] is different from ν, so this step preserves the invariant.

  • Termination
    The loop terminates when i>A.length. Since i increases by 1 and i>A.length, we know that all the elements in A have been checked and it has been found that ν is not among them. Thus, we return NIL.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值