The following is an exercise from my algorithms and datastructures course that aims to teach something about analysis of algorithms using loop-invariants.
The setup is the following; We have a jar with n marbles. A marble is either RED or BLUE. We also have an infinite pile of RED marbles. We aim to empty the jar by the use of this algorithm
The algorithm is as follows:
input: Jar with *n* marbles each of color RED or BLUE
i <- n
while i > 1 do
Pick two arbitrary marbles m1, m2 from the jar.
if Color(m1) == Color(m2) then
Throw the two marbles away
Place a RED marble in the jar
end
else
Throw away the RED marble
Put the BLUE marble back in the jar
end
i = i - 1
end
1) Argue that at the end of the algorithm we are left with 1 marble in the jar. My idea is here to say that we have a loop-invariant that is the following
At the beginning of an iteration of the while loop there are n-(n-i) marbles left
Then show that the invariant is true during Initialization, Maintenance and Termination however i am unsure as to how i should approach this could anyone help here?
E.g at initialization it is clear that the loop-invariant is the since we have n marbles in the jar and thus n-0 = n from the invariant but how should i approach the rest?