CS109A Notes For Lecture 1/24/96 Proving Recursive Programs Work
CS109A Notes For Lecture 1/24/96 Proving Recursive Programs Work
void convert(int i) {
if(i>0) {
convert(i/2);
putchar('0' + i%2);
}
}
Statement to be proved:
S (i): convert produces the binary representation of integer i 0.
Note that is the correct binary representation of 0 in this context.
Basis: i = 0. The test of line (1) fails, so is
printed.
Induction: Assume S (j ) for 0 j < i and prove
S (i) for i
0.
Note, we are breaking our habit of proving S (i + 1) from smaller cases; but it
doesn't matter whether we call the next
case to be proven i + 1 or i.
If i is even, say i = 2j , then convert prints
the binary representation of j at line (2) followed by 0 at line (3).
Appending the nal 0 multiplies the
value printed by 2, which gives the representation of 2j , or i.
1
Sorting
a2
an
a3
Mergesort
Splitting
Merging
Basis: If one list is empty, the other list is the
sorted result.
Example:
List1
(1; 1; 3; 4)
(1; 3; 4)
(3; 4)
(3; 4)
(4)
List2
(2; 5; 6; 9)
(2; 5; 6; 9)
(2; 5; 6; 9)
(5; 6; 9)
(5; 6; 9)
(5; 6; 9)
Result
(1)
(1; 1)
(1; 1; 2)
(1; 1; 2; 3)
(1; 1; 2; 3; 4)
(1; 1; 2; 3; 4; 5; 6; 9)