Question 2.7.2 
        a. What is the postcondition?
        b. What is the loop invariant?

Show ∀j: 1 ≤ j ≤ i, ∑aj = Pk ^ i n is always true
1. Base Step: before the loop,
         -- Precondition:  ∃a1
 c. Base step, show invariant holds:
         ∀j: 1 ≤ j ≤ i, ∑aj = Pk ^ i n

 

2. Inductive Step: Pk → Pk+1

at the end of each loop,
Assume (when loop executes)

i < n
∀j: 1 ≤ j ≤ i, ∑aj = Pk ^ i n

Show ∀j: 1 ≤ j ≤ i+1, ∑aj = Pk+1 ^ i+1 n

-- Precondition:  ∃a1
procedure Pn( a1, a2, a3, ..., an : integers)

Pk a1
i
1

∀j: 1 ≤ j ≤ i, ∑aj = Pk ^ i n
while  i < n

Pk+1 Pk + ai+1
i
i + 1
Pk Pk+1

d. Prove ∀j: 1 ≤ j ≤ i+1, ∑aj = Pk+1 ^ i+1 n
Note ∀j: 1 ≤ j ≤ i, ∑aj = Pk a1+ a2 ... + ai = Pk

 

 

 

 

 

 

 

 

 

 

 

 

3. and after the loop completes e. Prove when terminates: ∀j: 1 ≤ j ≤ i , ∑aj = Pk ^ i n

 

 

 

 

 

 

 

-- Precondition:  ∃an+1^∀j: 1 ≤ j < n, aj aj+1
procedure insert( x, a1, a2, a3, ..., an, an+1 : integers)

i 1

while  i < n ^ x > ai

i i + 1

x ⇔ ai

while  i n

i i + 1

x ⇔ ai

-- Postcondition:  ∀j: 1 ≤ j ≤ n, aj aj+1

i n+1 x ai
1 4 5
1 2 3 4
3 6 9 5
2 4 5
1 2 3 4
3 6 9 5
3 4 6
1 2 3 4
3 5 9 6
4 4 9
1 2 3 4
3 5 6 9

 

Insertion sort is relatively simple using insert module.

-- Precondition:  ∃a1
procedure insertionSort( a1, a2, a3, ..., an : integers)
        i
1
∀j: 1 ≤ j < i,  aj ai ^ i n
while  i < n

i i + 1

a insert( ai , a)

-- Postcondition:  ∀j: 1 ≤ j < n, aj aj+1

 

 

 

 

 

Question 2.7.3 

a. What is the postcondition?   

b. What is the loop invariant?   

1. Base Step:

-- Precondition:  ∃a1

i 1

c. Base step, show invariant holds:

∀j: 1 ≤ j < i,  aj aj+1 ^ i n

2. Inductive Step: Pk → Pk+1

at the end of each loop.

∀j: 1 ≤ j < i,  aj aj+1 ^ i n
while  i < n

i i + 1

a insert( ai , a)             

-- Postcondition:  ∀j: 1 ≤ j < n, aj aj+1

d. Assume what for Pk? Note that k=i.

 

e. Show what for Pk+1?

 

f. Prove ∀j: 1 ≤ j < i+1,  aj aj+1 ^ i+1 n

insert preconditions must hold,

where k=n=i: ∃ai+1^∀j: 1 ≤ j < i, aj aj+1

Assume k=i precondition true: ∀j: 1 ≤ j < i,  aj aj+1 ^ i < n

then use insert postconditions for k+1= i+1.

 

 

 

 

 

 

3. and after the loop completes g. Prove when loop terminates:

∀j: 1 ≤ j < i,  aj aj+1 ^ i n