This preview shows pages 1–2. Sign up to view the full content.
Homework 2 Solutions
February 21, 2010
Problem 1a (3 points)
Precondition:
N >
1 is a natural number.
A
is an array of
N
elements. Each element is either
red or blue.
Postcondition:
A
contains the same number of red and blue elements, and all the red elements
come before all blue elements.
Problem 1b (4 points)
Denote by
i
k
and
j
k
the values of
i
and
j
after the
k
th
iteration. The loop
invariant is
1. If
j
k
>
1, then
A
[1
...j
k

1] contains only red elements
2. If
i
k
> j
k
, then
A
[
j
k
...i
k

1] contains only blue elements.
We prove this by induction. The base case is the ﬁrst iteration, or
k
= 1. In the
case that
A
[1] is red, then
i
1
= 2 and
j
1
= 2, so to prove the LI we just need
to show that
A
[1] is red. The swap operation does not aﬀect the array since
i
0
=
j
0
. Therefore, the value of
A
[1] does not change and remains red. In the
case that
A
[1] is blue, then
i
1
= 2 and
j
1
= 1, so to prove the LI we need to
show that
A
[1] is blue. Since the if condition fails,
A
is not aﬀected and
A
[1]
remains blue.
For the general case, we will show that the loop invariants holds after
k
+ 1
iterations. First consider the case that
A
[
i
k
] =
red
. The only changes to
A
in
iteration
k
+ 1 are that the values of
A
[
i
k
] and
A
[
j
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.
 Spring '10
 FarzanAzadeh

Click to edit the document details