Professional Documents
Culture Documents
COMP108
COMP108
Algorithmic Foundation
Prudence Wong
http://www.csc.liv.ac.uk/~pwong/teaching/comp108
1
Algorithmic Foundations
COMP108
Module information …
2
Algorithmic Foundations
COMP108
Teaching Team
Dr Prudence Wong
pwong@csc.liv.ac.uk
Assignments Examination
& Quizzes 4
Algorithmic Foundations
COMP108
~36 lectures
(Mon 2-3pm, Wed 11am-12pm, Thu 10-11am)
A written examination
(80% of final mark)
Main Reference
Introduction to the Design
and Analysis of Algorithms
Anany V. Levitin
Villanova University
Addison Wesley
Additional Reading
Introduction to Algorithms
Thomas H. Cormen,
Charles E. Leiserson,
Ronald L. Rivest
The MIT Press
6
Algorithmic Foundations
COMP108
7
Algorithmic Foundations
COMP108
Why COMP108?
Pre-requisite for: COMP202, COMP209
(COMP202 is pre-requisite for COMP308, COMP309)
8
Algorithmic Foundations
COMP108
Aims
What do we mean by good?
¾ To give an overview of the study of algorithms in terms of
their efficiency.
How to achieve?
¾ To introduce the standard algorithmic design paradigms
employed in the development of efficient algorithmic
solutions.
Can we prove?
¾ To describe the analysis of algorithms in terms of the use of
formal models of Time and Space.
Can all problems be solved efficiently?
¾ To give a brief introduction to the subject of computational
complexity theory and its use in classifying computational
problems. 9
Algorithmic Foundations
COMP108
Ready to start …
10
Algorithmic Foundations
COMP108
Learning outcomes
¾ Able
to tell what an algorithm is and have
some understanding why we study algorithms
¾ Able to use pseudo code to describe algorithm
¾ Able to carry out simple asymptotic analysis
of algorithms
¾ Seesome examples of polynomial time and
exponential time algorithms
¾ Ableto apply searching/sorting algorithms and
derive their time complexities
11
Algorithmic Foundations
COMP108
Learning outcomes
¾ Able
to tell what an algorithm is and have
some understanding why we study algorithms
¾ Able to use pseudo code to describe algorithm
¾ Able to carry out simple asymptotic analysis
of algorithms
¾ Seesome examples of polynomial time and
exponential time algorithms
¾ Ableto apply searching/sorting algorithms and
derive their time complexities
12
Algorithmic Foundations
COMP108
What is an algorithm?
A sequence of precise and concise instructions
that guide you (or a computer) to solve a
specific problem
5 9 14
Algorithmic Foundations
COMP108
15
Algorithmic Foundations
COMP108
Number of routes
A =2
16
Algorithmic Foundations
COMP108
Number of routes
A =2+3
17
Algorithmic Foundations
COMP108
Number of routes
A =2+3
18
Algorithmic Foundations
COMP108
Number of routes
A =2+3+6
6 = 11
19
Algorithmic Foundations
COMP108
For large n, it is
A impossible to check all
routes!
We need more
sophisticated solutions
20
Algorithmic Foundations
COMP108
21
Algorithmic Foundations
COMP108
B
10 8
10 6
12 3 4
0 3
5 2 5
3
5
9
A 7 5
7
1 6 11
5 9 22
Algorithmic Foundations
COMP108
B
10 8
10 6
12 3 4
0 3
5 2 5
5 3
5
9
A 7 5
7
1 6 11
5 9 23
Algorithmic Foundations
COMP108
Again ...
B
10 8
10 6
12 3 4
0 3
5 2 5
5 3
5
9
A 7 5
7
1 6 11
5
7 9 24
Algorithmic Foundations
COMP108
B
10 8
10 6
12 3 4
0 3
5 2 5
5 3
5
9
A 7 5
7
1 6 11
5
7 9 25
Algorithmic Foundations
COMP108
B
10
8 8
10 6
12 3 4
0 3
5 2 5
5 3
5
9
A 7 5
7
1 6 11
5
7 9 26
Algorithmic Foundations
COMP108
17
B
8 8
10 6
12 3 4
0 3
5 2 5
5 3
5
9
A 7 5
7
1 6 11
5
7 9 27
Algorithmic Foundations
COMP108
?
B
8 8
10 6
12 3 4
0 3 ?
5 2 5 ?
5 3
5
A 7
9
5
? 7
1 6 11
5 ?
7 ?
9 28
Algorithmic Foundations
COMP108
Lesson to learn
29
Algorithmic Foundations
COMP108
Learning outcomes
9 Able
to tell what an algorithm is and have
some understanding why we study algorithms
¾ Able to use pseudo code to describe algorithm
¾ Able to carry out simple asymptotic analysis
of algorithms
¾ Seesome examples of polynomial time and
exponential time algorithms
¾ Ableto apply searching/sorting algorithms and
derive their time complexities
30
Algorithmic Foundations
COMP108
How to represent
algorithms …
31
Algorithmic Foundations
COMP108
Algorithm vs Program
Still remember? An algorithm is a sequence of precise and concise
instructions that guide a computer to solve a specific problem
33
Algorithmic Foundations
COMP108
Pseudo Code
p = 1
Another way to
while i <= n do
describe algorithm
begin
is by pseudo code
p = p * a
i = i+1
p = 1 end
for i = 1 to n do output p
p = p * a
output p
similar to programming
language
more like English Combination of both
34
Algorithmic Foundations
COMP108
while condition do
statement(s)
repeat
statement(s)
until condition
37
Algorithmic Foundations
COMP108
Learning outcomes
9 Able
to tell what an algorithm is and have
some understanding why we study algorithms
9 Able to use pseudo code to describe algorithm
¾ Able to carry out simple asymptotic analysis
of algorithms
¾ Seesome examples of polynomial time and
exponential time algorithms
¾ Ableto apply searching/sorting algorithms and
derive their time complexities
41
Algorithmic Foundations
COMP108
Analysis of algorithms …
42
Algorithmic Foundations
COMP108
Analysis of Algorithms
After designing an algorithm, we analyze it.
¾ Proof of correctness: show that the algorithm
gives the desired result
¾ Time complexity analysis: find out how fast the
algorithm runs
¾ Space complexity analysis: decide how much
memory space the algorithm requires
¾ Look for improvement: determine whether the
algorithm is best possible; can we improve it to run
faster or use less memory? 43
Algorithmic Foundations
COMP108
Proof of Correctness
There are different proof techniques:
¾ Direct Proof
¾ Proof by Cases
¾ Proof by Contradiction
¾ Proof by Mathematical Induction
¾…
44
Algorithmic Foundations
COMP108
Mathematical Induction
¾ Claim: 1+2+…+k = k(k+1)/2 for all positive integers k
¾ Denote p(k) as the statement "1+2+…+k = k(k+1)/2"
¾ Basic step: When k=1, 1+2+…+k = 1 = k(k+1)/2.
Therefore, p(1) is true.
¾ Induction step: Assume that p(k) is true for an integer
k ≥ 1. We need to prove that p(k+1) is true.
¾ 1+2+…+k+(k+1) = k(k+1)/2 + (k+1) = (k+1)(k/2+1) = (k+1)(k+2)/2
¾ Therefore, p(k+1) is true.
¾ Conclusion: p(k) is true for all positive integers
45
Algorithmic Foundations
COMP108
A nonsense induction
Claim: All COMP108 students are of the same gender.
Let us prove the claim by induction on the number of
students.
Basic step: Consider any group of COMP108 students
which comprises only one student. Same gender of
course.
Induction step: Assume that any group of n COMP108
students are of the same gender.
Next, we consider any group of (n+1) COMP108
students.
46
Algorithmic Foundations
COMP108
Proof of Correctness
Proof by Mathematical Induction (MI)
1. In the 0-th iteration, sum equals 0. Correct!
50
Algorithmic Foundations
COMP108
51
Algorithmic Foundations
COMP108
Amount of data handled
matches speed increase?
When computation speed vastly increased,
can we handle much more data?
Suppose
• an algorithm takes n2 comparisons to sort n numbers
• we need 1 sec to sort 5 numbers (25 comparisons)
• computing speed increases by factor of 100
Using 1 sec, we can now perform 100x25 comparisons,
i.e., to sort 50 numbers
With 100 times speedup, only sort 10 times more numbers!
52
Algorithmic Foundations
COMP108
We need n additions
(depend on the input size n)
53
Algorithmic Foundations
COMP108
56
Algorithmic Foundations
COMP108
Y a≤b? N
Y a≤c? Y b≤c? N
Y a≤c? Y b≤c? N
60
Algorithmic Foundations
COMP108
a2 ≤ a3 ? a2 ≤ a3 ?
62
Algorithmic Foundations
COMP108
min = 0
i=1
i = i+1
i < n? N
Y
Output a[min]
Y
min = i a[i] < a[min]?
N
63
Algorithmic Foundations
COMP108
65
Algorithmic Foundations
COMP108
Proof by induction
Let mini be the index of min value in a[0]...a[i].
Claim: After the i-th iteration, min stores mini.
1. Before any iteration (i=0), min stores 0 = min0
2. Assume after the k-th iteration, min stores mink
3. In the (k+1)-th iteration, a[mink] is compared with
a[k+1] and the index of the smaller value (i.e.,
mink+1) is stored in min
while (i < n) do
input a[0], a[1], ..., a[n-1] begin
min = 0 if (a[i] < a[min]) then
i = 1 min = i
i = i + 1
end
66
output min
Algorithmic Foundations
COMP108
67
Algorithmic Foundations
COMP108
Can we do better?
68
Algorithmic Foundations
COMP108
a4 ≤ a1 a6 ≤ a7 a6
a4
a4 ≤ a6 a4
a4 ≤ a1 a6 ≤ a7 a6
a4
a4 ≤ a6 a4
a1 ≤ a2 a4 ≤ a3 a6 ≤ a5 a7 ≤ a8
a1 a4 a6 a7
a4 a6 ≤ a7 a6
a4 ≤ a1
71
a4 ≤ a6 a4
Algorithmic Foundations
COMP108
Time complexity
- Big O notation …
72
Algorithmic Foundations
COMP108
1000000
100000
10000
Time
1000
f1(n)
f1(n) == 50n
50n++20
20
100 f2(n) ==10
f2(n) 10nnlog2n
log2n+ +100
100
f3(n) ==nn2
f3(n) 2 - 3n + 6
- 3n + 6
10 f4(n) ==2n
f4(n) 2
2n2
f5(n) ==22n/8
f5(n)
n/8 - n/4 + 2
- n/4 + 2
1
1 2 4 8 16 32 64 128 256 512 1024 2048 4096
n
74
Algorithmic Foundations
COMP108
What do we observe?
¾ There is huge difference between
¾ functions involving powers of n (e.g., n, n log n, n2,
called polynomial functions) and
¾ functionsinvolving powering by n (e.g., 2n, called
exponential functions)
¾ Among polynomial functions, those with same
order of power are more comparable
¾ e.g., f3(n) = n2 - 3n + 6 and f4(n) = 2n2
75
Algorithmic Foundations
COMP108
Big-O notation
f(n) = O(n log n) [read as f(n) is of order n log n]
¾ What does it mean? (note that log n is base 2).
¾ Roughly speaking, f(n) is at most n log n
multiplied by a constant
¾ e.g., f(n) = 3 n log n + 10n + 100
78
Algorithmic Foundations
COMP108
Hierarchy of functions
¾ We can define a hierarchy of functions each
having a greater order of magnitude than its
predecessor:
1 log n n n2 n3 ... nk ... 2n
log n
c
n
81
Algorithmic Foundations
COMP108
Exercise
Determine the least order of magnitude of the
following functions.
1. n3 + 3n2 + 3 O(n3)
2. 4n2 log n + n3 + 5n2 + n O(n3)
3. 2n2 + n2 log n O(n2 log n)
4. 6n2 + 2n O(2n)
83
Algorithmic Foundations
COMP108
More exercise
What is the time complexity of the following
pseudo code?
for i = 1 to 2n do
for j = 1 to n do
for k = 1 to j do
x = x + 1
O(?)
The outer-most loop iterates for 2n times.
The j-loop iterates for n times.
The k-loop iterates for j times, i.e., 1, 2, …, n.
Total: 2n * (1+2+...+n) = 2n* n(n+1)/2 = n2(n+1).85
Algorithmic Foundations
COMP108
Example
Question: Give an O(n2)-time algorithm to check
whether all numbers in an array are all
distinct.
Rough idea: For each number, check it is equal
to any of the other numbers. If yes, NOT
distinct. After checking all numbers, then
distinct.
Algorithm: Why O(n2)?
for i = 0 to n-2 do
for j = i+1 to n-1 do
if a[i] == a[j] then
output "Not distinct" and stop
output "distinct" 86
Algorithmic Foundations
COMP108
Summary
f(n) is O(g(n)) [read as f(n) is of order g(n)]
¾ There exists a constant c such that for all
sufficiently large n, f(n) ≤ c g(n)
¾ ∃c ∃no ∀n: if n>no then f(n) ≤ c g(n)
1 log n n n2 n3 ... nk ... 2n
Exercise
Are the followings correct?
1. n2log n + n3 + 3n2 + 3 O(n2)?
2. n + 1000 O(n)?
3. 6n20 + 2n O(n20)?
4. n3 + 5n2 log3n + n O(n2log3n) ?
88
Algorithmic Foundations
COMP108
Matrix Multiplication
Consider the multiplication of two nxn matrices
A and B.
What is the time complexity of the definition-
based algorithm?
A col j B C
x =
row i
C[i,j]
Time complexity:
The i-loop iterates for n times, in which
the j-loop iterates for n times, in which
the k-loop iterates for n times as well.
Total n3 iterations, each takes O(1) steps.
Therefore, time complexity is O(n3). 90
Algorithmic Foundations
COMP108
String Matching
Given a string of n characters called the text
and a string of m characters (m≤n) called the
pattern.
We want to find a substring of the text that
matches the pattern.
Example
text: N O B O D Y _ N O T I C E _ H I M
pattern: N O T
substring: N O B O D Y _ N O T I C E _ H I M
91
Algorithmic Foundations
COMP108
String Matching
N O B O D Y _ N O T I C E _ H I M
N O T
N O T
N O T
N O T
for i = 0 to n-m do N O T
N O T
begin N O T
j=0 N O T
while j < m & P[j]==T[i+j] do
j=j+1
if j == m then
report "found!" & stop
end
report "Not found!" 92
Algorithmic Foundations
COMP108
Time Complexity
How many comparisons this algorithm requires?
Best case: for i = 0 to n-m do
pattern appears in the begin
beginning of the text, j=0
while j < m & P[j]==T[i+j] do
O(m)-time j=j+1
Worst case: pattern if j == m then
report "found!" & stop
appears at the end of end
the text OR pattern report "Not found!"
does not exists,
O(nm)-time
93
Algorithmic Foundations
COMP108
Space Complexity
We need to store the n characters of the text,
the m characters of the pattern, the variables i,
j, m and n
=> need n+m+4 memory space, O(n+m)-space
for i = 0 to n-m do
begin
j=0
while j < m & P[j]==T[i+j] do
j=j+1
if j == m then
report "found!" & stop
end
report "Not found!" 94
Algorithmic Foundations
COMP108
Learning outcomes
9 Able
to tell what an algorithm is and have
some understanding why we study algorithms
9 Able to use pseudo code to describe algorithm
9 Able to carry out simple asymptotic analysis
of algorithms
¾ Seesome examples of polynomial time and
exponential time algorithms
¾ Ableto apply searching/sorting algorithms and
derive their time complexities
95
Algorithmic Foundations
COMP108
96
Algorithmic Foundations
COMP108
Searching
Input: a sequence of n numbers a0, a1, …, an-1;
and a number X
Output: determine whether X is in the sequence
or not
Algorithm (Linear search):
1. Starting from i=0, compare X with ai one by one
as long as i < n.
2. Stop and report "Found!" when X = ai .
3. Repeat and report "Not Found!" when i >= n.
97
Algorithmic Foundations
COMP108
Linear Search
¾ 12 34 2 9 7 5 six numbers
7 number X
¾ 12 34 2 9 7 5
7
¾ 12 34 2 9 7 5
7
¾ 12 34 2 9 7 5
7
¾ 12 34 2 9 7 5
7 found!
98
Algorithmic Foundations
COMP108
Time Complexity
i=0
while i < n do
Important operation of begin
searching: comparison if X == a[i] then
report "Found!" & stop
How many comparisons this else
algorithm requires? i = i+1
end
report "Not Found!"
103
Algorithmic Foundations
COMP108
Binary Search
more efficient way of searching when the sequence
of numbers is pre-sorted
Input: a sequence of n sorted numbers a0, a1, …, an-1;
and a number X
Idea of algorithm:
¾ compare X with number in the middle
¾ then focus on only the first half or the second half
(depend on whether X is smaller or greater than the
middle number)
¾ reduce the amount of numbers to be searched by half
104
Algorithmic Foundations
COMP108
19 24 33 41 55
24
19 24
24
24
24 found!
105
Algorithmic Foundations
COMP108
19 24 33 41 55
30
19 24
30
24
30 not found!
106
Algorithmic Foundations
COMP108
Time Complexity
Best case:
first=0, last=n-1
X is the middle number while (first <= last) do
=> 1 comparison, O(1)-time begin
mid = (first+last)/2
Worst case: if (X == a[mid])
at most log2n+1 comparisons, report "Found!" & stop
O(log n)-time else
if (X < a[mid])
Why? Every comparison last = mid-1
reduces the amount of else
first = mid+1
numbers by at least half end
E.g., 16 => 8 => 4 => 2 => 1 report "Not Found!"
108
Algorithmic Foundations
COMP108
110
Algorithmic Foundations
COMP108
111
Algorithmic Foundations
COMP108
Sorting
Input: a sequence of n numbers a0, a1, …, an-1
Output: arrange the n numbers into ascending
order, i.e., from smallest to largest
Example: If the input contains 5 numbers 132,
56, 43, 200, 10, then the output should be 10,
43, 56, 132, 200
Selection Sort
¾ find minimum key from the input sequence
¾ delete it from input sequence
¾ append it to resulting sequence
¾ repeat until nothing left in input sequence
113
Algorithmic Foundations
COMP108
115
Algorithmic Foundations
COMP108
Algorithm Analysis
for i = 0 to n-2 do
The algorithm consists of a begin
nested for-loop. min = i
for j = i+1 to n-1 do
For each iteration of the if a[j] < a[min] then
min = j
outer i-loop, swap a[i] and a[min]
there is an inner j-loop. end
Bubble Sort
starting from the last element, swap adjacent
items if they are not in ascending order
when first item is reached, the first item is the
smallest
repeat the above steps for the remaining items
to find the second smallest item, and so on
117
Algorithmic Foundations
COMP108
119
Algorithmic Foundations
COMP108
34 10 64 51 32 21
i =0 j=5
j=4
j=3
j=2
j=1
i =1 j=5
j=4
j=3
j=2
120
Algorithmic Foundations
COMP108
Algorithm Analysis
The algorithm consists of a nested for-loop.
for i = 0 to n-1 do
for j = n-1 downto i+1 do
if (a[j] < a[j-1])
swap a[j] & a[j-1]
Sorting
Input: a sequence of n numbers a0, a1, …, an-1
Output: arrange the n numbers into ascending
order, i.e., from smallest to largest
122
Algorithmic Foundations
COMP108
Insertion Sort
look at elements one by one
build up sorted list by inserting the element at
the correct location
123
Algorithmic Foundations
COMP108
Example
¾ sort (34, 8, 64, 51, 32, 21) in ascending order
Sorted part Unsorted part int moved
34 8 64 51 32 21
34 8 64 51 32 21 -
8 34 64 51 32 21 34
8 34 64 51 32 21 -
8 34 51 64 32 21 64
8 32 34 51 64 21 34, 51, 64
8 21 32 34 51 64 32, 34, 51, 64
124
Algorithmic Foundations
COMP108
Algorithm Analysis
for i = 1 to n-1 do
Worst case input begin
key = a[i]
¾ input
is sorted in pos = 0
while (a[pos] < key) && (pos < i) do
descending order pos = pos + 1
shift a[pos], …, a[i-1] to the right
Then, for a[i] a[pos] = key
end
¾ finding
the position takes i
comparisons i # of comparisons in
the while loop
total number of comparisons 1 1
= 1 + 2 + … + n-1 2 2
= (n-1)n/2 O(n2)-time
… ...
n-1 n-1
126
Algorithmic Foundations
COMP108
127
Algorithmic Foundations
COMP108
128
Algorithmic Foundations
COMP108
This is known as
Hamiltonian circuit
129
Algorithmic Foundations
COMP108
Example a
2
b
To find a Hamiltonian
7 8 3 circuit from a to a
5
c d
1
Tour Length
a -> b -> c -> d -> a 2 + 8 + 1 + 7 = 18
a -> b -> d -> c -> a 2 + 3 + 1 + 5 = 11
a -> c -> b -> d -> a 5 + 8 + 3 + 7 = 23
a -> c -> d -> b -> a 5 + 1 + 3 + 2 = 11
a -> d -> b -> c -> a 7 + 3 + 8 + 5 = 23
a -> d -> c -> b -> a 7 + 1 + 8 + 2 = 18 130
Algorithmic Foundations
COMP108
Knapsack Problem
Input: Given n items with weights w1, w2, …, wn
and values v1, v2, …, vn, and a knapsack with
capacity W.
Output: Find the most valuable subset of items
that can fit into the knapsack.
Application: A transport plane is to deliver the
most valuable set of items to a remote
location without exceeding its capacity.
132
Algorithmic Foundations
COMP108
Example
capacity = 10
2n, why?
134