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
- Initialization: It is true prior to the first iteration of the loop.
- Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration.
- 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.