Transcript Chapter 5

CS 345: Chapter 5
Correctness of Algorithms
Winter, 2016
Errors
• “To Err Is Human…”
• In a program, we distinguish between
– Syntax Errors
– Run-Time Errors
– Logical or Algorithmic Errors
Correctness
• An algorithmic problem can be divided into
two parts:
– Specification of the set of legal inputs.
– Relationship between inputs and outputs.
• We can classify an algorithm with two types
of correctness:
– Partial Correctness
– Total Correctness
Partial Correctness
• Algorithm A is Partially Correct if
(1) It is given a legal input.
(2) If it terminates, then its output is correct.
• Note that the algorithm may not terminate on
all legal inputs; but, when it does terminate,
it gives the correct output.
Total Correctness
• Algorithm A is totally correct if, whenever
A is run on a legal input, it terminates with
the correct output.
• Another way to say this: Algorithm A is
totally correct if it is partially correct, and it
terminates on all legal inputs.
Automatic Verifier
• An automatic verifier is a super-algorithm
that takes for input a description of an
algorithmic problem P and an algorithm A
and determines if A correctly solves P.
• Unfortunately, it can be shown that no such
automatic verifier can be constructed.
Invariant Assertion Method
• Also called Floyd’s method, this is one
approach to proving correctness.
– Divide the algorithm into simple paths that are
entered and exited at checkpoints.
– Attach an intermediate assertion to each
checkpoint. This is a statement claimed to be
true when execution reaches that point.
• Because each simple path may be traversed
many times, an assertion is often called an
invariant: a statement that is true no matter
how many times it is reached.
• Partial Correctness is shown using these
invariants.
• Total Correctness is shown using a
convergent.
• Example: Reversing A String, pp. 110-114