Professional Documents
Culture Documents
(CS210A)
Lecture
5:
PROOF OF CORRECTNESS
sum of numbers
from to
Sum_of_Numbers()
{ Sum;
for = 1 to
{
Sum Sum + ;
}
return Sum;
}
Natural responses:
It is obvious !
Compile it and run it for some random values of .
Go over first few iterations explaining what happens to
Sum.
4
Proof of correctness
For an iterative algorithm
Asserti
on
P()
Start
of Loop
on
P()
Iterations
Prove P() by
What would you
expect at the end
1. Assuming
?
P()
of th iteration ?
2.Theorem
?
Proof by induction
3.Body
? of the Loop
The most difficult/creative part of
: with the right
?
To proof
come
up
assertion P()
7
sum of numbers
from to
Sum;
for = 1 to
{
{
Sum Sum + ;
}
return Sum;
}
Assertion
: ? of th iteration Sum stores the sum of numbers from t
At P()
the
end
Base case: P() holds.
Assuming P(), assertion P() also holds.
P() holds.
8
S[] A[]
for = 1 to
{
If S[] > 0 then S[] S[] + A[]
else S[] A[]
}
Scan S to return the maximum entry
}
Assertion
? sum of maximum sum subarray ending at A[].
S[]P()
stores
:
the
Homework: Prove that P() holds for all
9
10
31
5 33 10
99
11
31
5 33 10
99
12
13
A new approach
Repeat : if current entry is not local minima, explore the neighbor
storing smaller value.
j
14
A new approach
Explore()
{
Let c be any entry to start with;
While(c is not a local minima)
{
c a neighbor of c storing smaller value
}
return c;
}
15
A new approach
Explore()
{
Let c be any entry to start with;
While(c is not a local minima)
{
c a neighbor of c storing smaller value
}
return c;
}
First principle:
Do not discard
Explore()
Second principle:
Simplify the problem
16
1
7
2
3
17 23
2
3
17 23
int
Local-minima-in-array(A) {
O(log )
L 0;
How many
R;
iterations ?
found FALSE;
while( not ??
)
found
{
(L + R)/2;
If ( is a local minima)
O()
time
found TRUE;
in one iteration
else if(A[] < A[])
??
;
L
else
R??
}
return ; }
Proof of
Running time of the algorithm = O(log )
correctness ?
19
A
P() : At the end of th iteration,
A local minima of array A exists in A[,, ].
20
A
P() : At the end of th iteration,
A local minima of array A exists in A[,, ].
=
A[]< A[] and A[]< A[].
Homework:
Make sincere attempts to prove the assertion P().
How will you use it to prove that Local-minima-in-array(A)
21
outputs a local minima ?
22
circumstances
exists
Search for a local minima in the column M[, ] What
if there is no
Execute
Explore() from
M[, ]
Smallest element
of the column
even
smallest
in
thisthis
region.
local
minima
in
element
is
not
a
Whyentire
?
the
column.
local minima ?
9 7
Homework:
Use this idea to design an O(log ) time algorithm for this
problem.
23
24