# hw2 - then the loop will terminate. PreCondition: x,y ∈ Z...

This preview shows pages 1–2. Sign up to view the full content.

CSC236H: Introduction to the Theory of Computatoin Homework 2 Due on Tuesday Feb 9, 2010 (in class) 1. Consider an array A [1 ..N ] each of whose elements is red or blue . The following algorithm rearranges the elements of A so that all occurrences of red come before all occurrences of blue . The algorithm makes use of a swap operation which, as the name suggests, swaps the contents of two cells. i = 1 j = 1 while ( i N ) { if ( a [ i ] is red ) { swap( a [ i ], a [ j ]) j = j + 1 } i = i + 1 } (a) Write down the precondition and the postcondition for the above algorithm that matches the above description. (b) Prove that the algorithm is partially correct by ﬁnding (and proving) the proper loop invariant. (c) Quickly argue why this program terminates (Note: this is a very simple and short argument). 2. Consider the following program and the given pre/post-conditions. Prove that if the preconditions are true

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: then the loop will terminate. PreCondition: x,y ∈ Z ,z ∈ N . while ( x 6 = y and z ≥ 0) { if ( x > y ) { x = x - z; } else { y := y-z ; } z = z-1; } PostCondition: True. 3. Consider an array A [1 ..N ] with integer elements. The following algorithm recursively ﬁnds and returns the smallest element in the array. MIN ( A,f,l ) if ( f = l ) { return A[f] } m = ( f + l ) div 2 a = MIN ( A,f,m ) b = MIN ( A,m + 1 ,l ) if ( a < b ) { return a } else { return b } 1 (a) Write down the precondition and the postcondition for the above algorithm (Hint: your postcondition should include the fact that the return value is the smallest element of array A ). (b) Prove that the algorithm is correct (do not forget about termination). 2...
View Full Document

## This note was uploaded on 04/11/2010 for the course CSC CSC236 taught by Professor Farzanazadeh during the Spring '10 term at University of Toronto- Toronto.

### Page1 / 2

hw2 - then the loop will terminate. PreCondition: x,y ∈ Z...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online