Algorithm Correctness and Time Complexity
Algorithm Correctness and Time Complexity
Time Complexity
Ric Glassey
glassey@kth.se
Outline
• Correctness
– Aim: Proving the correctness of algorithms
– Loop Invariants
– Mathematical Induction
• Time Complexity
– Aim: Determining the cost of recursive algorithms
– Recursion reminder
– Expressing recursive algorithms as recurrences
– Applying the Master Theorem
2
CORRECTNESS
3
What is Correctness?
4
Why not just test?
5
Adopt more formalism
• We can express our algorithms as mathematical
entities and use various strategies to prove
correctness (rather than guess work)
• However, this is an expensive process...
– That is, the cost up front is expensive
– The benefits come late (contradicts time to market)
– Yet, software estimation is more art than science
• Money, time, developers
• As a rule...take your best guess and multiply it by 3 ;-)
– But can be useful for algorithms in particular
• Two approaches considered here:
– Loop Invariants
– Mathematical Induction
6
Invariants
• In English: adjective never changing
7
Loop Invariants
• Non-trivial algorithms involve forms of looping
– Iteration
– Recursion
• Loop invariants allow logical assertions about
the behaviour of the loop to be declared
– Can be implicitly documented as comments
– Can be explicitly coded as a condition or assertion
• By establishing the correctness of looping
behaviour, we can move towards correctness of
an algorithm
– As well as understand better the effects of the loop
8
Loop Invariants: Sum
/
**
*
Returns
the
sum
1
+
2
+
...
+
n,
where
n>
=
1st
*
/
public
long
sum
(int
n)
{
long
sum
=
0;
int
i
=
1;
while
(i
<=
n)
{
//
Invariant:
sum
=
1
+
2
+
...
+
(i
-‐
1)
sum+
=
i;
i
++;
}
return
sum;
}
9
Loop Invariants: Good Properties
10
Loop Invariants: In design of max( )
/
**
*
Returns
the
max
value
in
the
vector
v.
*
/
public
int
max
(int
[]
v)
{
int
max
=
...;
for
(int
i
=
0;
i
<v.length;
i
++)
{
//
Invariant:
max
=
max
(v[0],
v[1],
...,
v[i-‐1])
...
}
return
max;
}
We
can
see
that
it
sa+sfies
the
‘conclusion’
characteris+c,
but
there
is
an
issue:
Loop
Invariant
must
be
true
at
the
start
of
the
loop
-‐
what
is
the
problem?
11
Loop Invariants: In design of max( )
/
**
*
Returns
the
max
value
in
the
vector
v,
where
v.length
>
0
*
*throws
IllegalArgumentException
if
v.length
=
0
*
/
public
int
max
(int
[]
v)
{
if
(v.length
==
0)
throw
new
IllegalArgumentException
("v.length
=
0");
int
max
=
...;
for
(int
i
=
1;
i
<v.length;
i
++)
{
//
Invariant:
max
=
max
(v[0],
v[1],
...,
v[i-‐1])
...
}
return
max;
}
12
Loop Invariants: In design of max( )
/
**
*
Returns
the
max
value
in
the
vector
v,
where
v.length
>
0
*
*throws
IllegalArgumentException
if
v.length
=
0
*
/
public
int
max
(int
[]
v)
{
if
(v.length
==
0)
throw
new
IllegalArgumentException
("v.length
=
0");
int
max
=
v
[0];
for
(int
i
=
1;
i
<v.length;
i
++)
{
//
Invariant:
max
=
max
(v
[0],
v
[1],
...,
v
[i-‐1])
if
(v
[i]>
max)
{
max
=
v
[i];
}
}
return
max;
}
13
Afterthought...Class Invariants
• In Java, it is typical to encode some invariants
into classes
– e.g. a Date class only permits hours from >=0 to <24
• The main idea is that class methods ensure that
there are no violations of the invariant
– A form of defensive programming; or presuming
the worst will probably happen
– Although there may be temporary changes
internally
• Java has no default syntax for invariant
– Standard expressions and assertions can be used
– 3rd Party efforts like Java Modelling Language
14
Mathematical Induction
n
statement
result
1
31
-‐
1
=
3
-‐
1
2
2
32
-‐
1
=
9
-‐
1
8
3
33
-‐
1
=
27
-‐
1
26
...
...
...
n
-‐
1
3n-‐1
-‐
1
?
n
3n
-‐
1
?
15
Mathematical Induction: Domino Effect
16
Mathematical Induction
• Process
– Base Case: Prove that the statement holds for the
first natural number (usually 1 or 0)
• e.g. for P(n) = 3n - 1
• base case is P(1) = 31 - 1 = 2
• which is clearly true as 2 is a multiple of 2
– Induction Step: prove that, if the statement holds
for some natural number k, then the statement holds
for k + 1
P(k)
=
3k
-‐
1
is
assumed
to
be
true
P(k+1)
=
3k+1
-‐
1
=
3
*
3k
-‐
1
=
3k
+
3k
+
3k
-‐1
=
(2
*
3k)
+
(3k
-‐
1)
17
18
Mathematical Induction: Sum
Base
Case:
P(1)
=
1
(directly
written
in
conditional
statement)
Induction
Step:
P(k)
=
k
+
P(k
-‐
1)
is
assumed
to
be
true
We
choose
P(k-‐1)
for
our
next
step
(why?)
We
know
that
P(k
-‐
1)
=
1
+
2
+
...
+
(k
-‐
1)
So:
k
+
(1
+
2
+
...
+
(k
-‐
1))
=
1
+
2
+
...
+
(k
-‐
1)
+
k
21
Mathematical Induction & Loop Invariants
• You may have noticed a similarity...
– Loop Invariants ideally have:
• Initialisation
• Update
• Conclusion
– Mathematical Induction involves:
• Base Case
• Induction Step
• Proof
– The loop invariant should tell us about the starting point P(1),
then the progress of the loop, such that we can create an
inductive proof for P(k) and all next steps P(k+1)
– We might not always have a convenient mathematical form to
prove (e.g. more complex data structures involved), but we can
still use invariants and induction to reason and prove algorithm
behaviour (for good design and documentation)
22
Readings 1
• Loop invariants ** required **
– http://www.nada.kth.se/~snilsson/algoritmer/loopinvariant/
– Example 3 in particular
• Induction & recursion ** required **
– http://www.nada.kth.se/~snilsson/algoritmer/induktion/
23
TIME COMPLEXITY
24
Progress and Running Time
• Invariants not only tell us something about the
progress of an algorithm:
– e.g. For a sorting algorithm
• So far, all items are sorted up to some n [progress]
• They can tell us about running time or cost
– e.g. For a sorting algorithm
• The worst case performance will be O(n2) [running time]
26
Visualising Binary Search
1 2 3 ... 98 99 100
x > 50?
1 2 3 ... 48 49 50
1 2 3 ... 23 24 25
27
Expressing Recurrences: Binary Search
• It is beneficial to express our recursive function as a
recurrence in order to reason about its behaviour
and work towards estimating its time complexity
• Let T(n) be the number of questions in binary
search on a range of numbers between 1 and n,
assuming n is a power of 2, then we have:
28
Mergesort
30
Expressing Recurrences: Mergesort
31
Recursion Tree for Mergesort
35
Readings 2
• Time complexity ** required
– http://www.nada.kth.se/~snilsson/algoritmer/rekursion/
• Introduction to recursion and recurrences
– https://math.dartmouth.edu/archive/m19w03/
public_html/Section4-2.pdf
– https://math.dartmouth.edu/archive/m19w03/
public_html/Section5-1.pdf
• Master Theorem
– https://math.dartmouth.edu/archive/m19w03/
public_html/Section5-2.pdf
– Nice and easy video on Master Theorem + Mergesort :-)
https://www.youtube.com/watch?v=B_TJcOaiJiU
36