Title: CS211 Spring 2004 Lecture 06 Loops and their invariants
1CS211 Spring 2004 Lecture 06Loops and their
invariants
Reading material These notes. Weiss Nothing on
invariants. ProgramLive Chapter 7 and 8
O! Thou hast damnable iteration and art, indeed,
able to corrupt a saint. Shakespeare, Henry IV,
Pt I, 1 ii Use not vain repetition, as the
heathen do. Matthew V, 48 Your if is the only
peacemaker much virtue if if. Shakespeare, As
You Like It.
2Software engineering reason for using loop
invariants
/ Token Scan.getToken() is first token of a
sentence for E. Parse it, giving error
messages if there are mistakes. After the parse,
Scan.getToken() should be the symbol following
the parsed E. Rule E T lt -gt T
/ public static void parseE() Expression
exp parseT() Token token Scan.getToken()
int kind token.getKind() while (kind
Token.PLUS kind Token.MINUS)
Scan.scan() Expression right parseT()
exp new BinOp(exp, token, right) token
Scan.getToken() kind token.getKind()
return exp
To understand any single part of the loop, you
first have to understand the whole loop and its
initialization! That is BAD BAD BAD!!!
3Software engineering reason for using loop
invariants
Rule E T lt -gt T / public
static void parseE() Expression exp
parseT() Token token Scan.getToken() int
kind token.getKind() // invariant exp is the
object for the expression parsed so far //
token is next token to process and
kind is its kind while (kind Token.PLUS
kind Token.MINUS) Scan.scan()
Expression right parseT() exp new
BinOp(exp, token, right) token
Scan.getToken() kind token.getKind()
// R exp is the object for the expression
parsed so far // token is the next
token to process, and its not part of this
E return exp
invariant is true before and after each iteration
4Software engineering reason for using loop
invariants
Rule E T lt -gt T / public
static void parseE() Expression exp
parseT() Token token Scan.getToken() int
kind token.getKind() // invariant exp is the
object for the expression parsed so far //
token is next token to process and
kind is its kind
Loop question 1. Does the initialization make the
invariant true?
5Software engineering reason for using loop
invariants
Rule E T lt -gt T / public
static void parseE() // invariant exp
is the object for the expression parsed so
far // token is next token to
process and kind is its kind while (kind
Token.PLUS kind Token.MINUS) //
R exp is the object for the expression parsed
so far // token is the next token to
process, and its not part of this E
Loopy question 2. When does loop stop? Can we
tell that result R is true based on the invariant
and the fact that the loop condition is false?
6Software engineering reason for using loop
invariants
Rule E T lt -gt T / public
static void parseE() // invariant exp
is the object for the expression parsed so
far // token is next token to
process and kind is its kind while ( )
Scan.scan() Expression right parseT()
Loopy question 3. Does each iteration make
progress toward termination?
7Software engineering reason for using loop
invariants
Rule E T lt -gt T / public
static void parseE() // invariant exp is the
object for the expression parsed so far //
token is next token to process and
kind is its kind while (kind Token.PLUS
kind Token.MINUS) Scan.scan()
Expression right parseT() exp new
BinOp(exp, token, right) token
Scan.getToken() kind token.getKind()
Loopy question 4. Does each iteration keep the
invariant true?
8The four loopy questions
initialization // invariant P while ( B)
S // R initialization // P while (
B ) // P and B S // P //
P and ! B // R
- Does the initialization make P true?
- From P and falsity of B, can we conclude that R
is true? - Does each iteration make progress toward
termination? - Does each iteration keep P true?
9About array segments bh..k-1
h k
?
b
has k - h elements
h h3
b bh..h3-1 has
h3 - h 3 elements
h h2
b bh..h2-1 has h2
- h 2 elements
h h1
b bh..h1-1 has
h1 - h 1 elements
bh..h0-1 has
h0 - h 0 elements bh..h-1 is the empty
segment starting at bh In the notation
bi..j, we always require i j1
10Linear search Find first occurrence of v in
bh..k-1
Better spec. Store an integer in i to
truthify postcondition (0) v is not in
bh..i-1 (1) Either i k or v
bi
h k
Precondition b Postcondition b
? and (i
k or v bi) Obviously, start the search
from bh, move forward. What is the
invariant? What is the formula for the number of
values in bh..i-1? i - h
?
h i k
v is not here
11Linear search Find first occurrence of v in
bh..k-1
h k
Precondition b i h //
invariant b
? while (i ! k v ! bi)
i i1 Postcondition b
? and (i
k or v bi)
?
12Binary search find v in sorted segment bh..k-1
h k
sorted
Precondition b Store in j to
truthify Postcondition b If v is in b,
then bj is its rightmost occurrence. If v is
not in b, then v belongs right after bj. What
if bh..k-1 is empty? That is, what if k
h? Set j to h-1, because then bh..j is
bh..h-1 (empty) and bj1..k-1 is bh..h-1
(empty)
See Weiss 5.6.2 and ProgramLive Section 8.5.3
13Binary search find v in sorted segment bh..k-1
h k
Precondition b Postcondition
b invariant b initialize j
h-1 i k
? (sorted)
14Binary search find v in sorted segment bh..k-1
h k
Precondition b Postcondition
b invariant b j h-1 i k
while ( ? ) When
can it stop? When should it continue?
? (sorted)
15Binary search find v in sorted segment bh..k-1
h k
Precondition b Postcondition
b invariant b j h-1 i k
while ( j 1 lt i ) How
does it make progress toward termination?
? (sorted)
16Binary search find v in sorted segment bh..k-1
h k
Precondition b Postcondition
b invariant b
? (sorted)
- Finds rightmost value, if in.
- Finds position where value belongs, if not in.
- Works on an empty array.
j h-1 i k while ( j 1 lt i )
int e (ji) / 2 // j lt e lt
i if (be lt v) j e else i
e
17Buggy Binary Search from a new text on programming
/Search (sorted) b for target using a binary
search. If found, store its position in p,
otherwise store -1 in p / int start 0 //
start of search region int end b.length // end
of search region int p -1 // position of
target // while there is still something list
left to search and the element has not been //
found while (start lt end position -1)
int middle (startend)/2 if ( target lt
bmiddle) end middle - 1 else if (target gt
bmiddle) start middle 1 else position
middle
fails if b.length 1, b0 0, and target 1
18Buggy Binary Search from a 2002 text on
programming
/Search (sorted) b for target using a binary
search. If found, store its position in p,
otherwise store -1 in p / public static int
execute(int b, int target) int lo 0
int hi b.length while (true) int
centre (hilo)/2 if (centre lo) //
only 2 items to test so it is centre, centre1,
or not in if (bcentre target)
return centre else (bcentre1
target) return center1 else return -1
if (bcentre lt target) lo centre
else if (target lt bcentre) hi centre
else return centre
subscript out of range if b.length 2, b0
10 b1 20 target 30
19Buggy Binary Search from a 2002 text on
programming
- The mistakes are logical errors, not simple
typos. - The comments are generally not helpful.
- Variables names give no help at all, in fact are
misleading - int start 0 // start of search region
- int end b.length // end of search region
- int lo 0 int hi b.length
- Neither text, like most texts, give absolutely
no help on how to develop such algorithms. You
either can do it or you cant and you can see
that the authors cant. - Weiss (page 169) says that binary search is
surprisingly tricky to code. Thats because he
does not follow a methodology for developing
loops. - You can choose your style. Program like these
texts, getting not only difficulty to understand
and complicated code, or learn a simple way of
developing loops using invariants and definitions
of variables.
20Dutch national flag b contains red, white, and
blue balls.
0
n
precondition b ?
what invariant to use?
0
n
postcondition b reds
whites blues
21Dutch national flag b contains red, white, and
blue balls.
0
n
precondition b ?
0
n
invariant b reds
whites blues ?
How to make progress in the repetend? (body of
the loop, the thing to be repeated).
0
n
postcondition b reds
whites blues
22Dutch national flag b contains red, white, and
blue balls.
0
n
precondition b ?
0 w h
k n
invariant b reds
whites blues ?
Cases bk is blue increment k bk is white
swap bh, bk, increment h and k bk is red
swap bh, bk swap bh, bw
increment k, h, and w
0
n
postcondition b reds
whites blues
23Dutch national flag b contains red, white, and
blue balls.
0
n
precondition b ?
0 w h
k n
invariant b reds
whites ? blues
Cases bh is blue Swap bh, bk decrement
k bk is white increment h bk is red swap
bh, bw increment h and w
0
n
postcondition b reds
whites blues
24Dutch national flag b contains red, white, and
blue balls.
0
n
precondition b ?
w 0 h 0 k n-1 while (h lt k) if
(bh is blue) swap bh, bk k k-1
else (bh is white) h h1 else Swap bh,
bw h h1 w w1
0 w h
k n
// invariant b reds
whites ? blues
0
n
postcondition b reds
whites blues
25Partition algorithm of quicksort (which we will
see later)
Plive, Sec. 8.5 (look at CD), Weiss, page 298
h
k
precondition b x ?
(x is not a program variables it is used just
to show what is initially in bh) Permute the
values of bh..k and store a value in j to
truthify initial bh..k 4
6 8 2 4 1 7 8 possible final
bh..k 2 1 4 4 8 6 7
8 possible final bh..k 1 2 4 4 8
6 8 7
bj
26Partition algorithm of quicksort (which we will
see later)
h
k
precondition b x ?
h j
k
R1 b x lt x
gt x
Swap bh and bj
27Partition algorithm of quicksort (which we will
see later)
h
k
precondition b x ?
h i j
k
invariant b x lt x
? gt x
28Partition algorithm of quicksort (which we will
see later)
h
k
precondition b x ?
i h1 j k while (i lt j) if (bi
lt x) i i1 else Swap bi, bj j
j-1
h i j
k
invariant b x lt x
? gt x