Greedy Algorithm
Greedy Algorithm
Application: Optimal
Caching
Algorithms: Design
and Analysis, Part II
The Caching Problem
Small fast memory (the cache).
Tim Roughgarden
Example
Cache: a b c d
e f
Request sequence: c d e f a b
⇒ 4 page faults
- 2 were inevitable (e & f)
- 2 consequences of poor eviction choices (should have
evicted c & d instead of a & b)
Tim Roughgarden
The Optimal Caching Algorithm
Theorem: [Bélády 1960s] The “furthest-in-future” algorithm is
optimal (i.e., minimizes the number of cache misses).
Why useful?
1. Serves as guideline for practical algorithms (e.g., Least
Recently Used (LRU) should do well provided data exhibits
locality of reference).
2. Serves as idealized benchmark for caching algorithms.
Tim Roughgarden
Greedy Algorithms
Introduction
Algorithms: Design
and Analysis, Part II
Algorithm Design Paradigms
Algorithm Design: No single “silver bullet” for solving problems.
Design Paradigms:
- Divide & conquer (see Part I)
- Randomized algorithms (touched in Part I)
- Greedy algorithms (next)
- Dynamic programming (later in Part II)
Tim Roughgarden
Greedy Algorithms
“Definition”: Iteratively make “myopic” decisions, hope everything
works out at the end.
Tim Roughgarden
Contrast with Divide & Conquer
1. Easy to propose multiple greedy algorithms for many problems.
Tim Roughgarden
In(correctness)
Example: Dijkstra’s algorithm with negative edge lengths. What
does the algorithm compute as the length of a shortest s-w path,
and what is the correct answer?
s 3 v
2 −2
A) 2 and 2 C) 1 and 2
B) 2 and 0 D) 2 and 1
Tim Roughgarden
Proofs of Correctness
Method 1: Induction. (“greedy stays ahead”)
Tim Roughgarden
Greedy Algorithms
A Scheduling Application:
Problem Definition
Algorithms: Design
and Analysis, Part II
A Scheduling Problem
Setup:
- One shared resource (e.g., a processor).
- Many “jobs” to do (e.g., processes).
Tim Roughgarden
Completion Times
Definition: The completion time Cj of job j = Sum of job lengths
up to and including j.
Example: 3 jobs, l1 = 1, l2 = 2, l3 = 3.
Schedule:
#1 #2 #3
0→
(time)
Question: What is C1 , C2 , C3 ?
A) 1, 2, 3 C) 1, 3, 6
B) 3, 5, 6 D) 1, 4, 6
Tim Roughgarden
The Objective Function
Goal:PMinimize the weighted sum of completion times:
min nj=1 wj Cj .
Tim Roughgarden
Greedy Algorithms
A Scheduling Application:
The Algorithm
Algorithms: Design
and Analysis, Part II
Intuition for Algorithm
Pn
Recall: Want to min j=1 wj .
A) Larger/shorter C) Larger/longer
B) Smaller/shorter D) Smaller/longer
Tim Roughgarden
Resolving Conflicting Advice
Question: What if wi > wj but li > lj ?
Tim Roughgarden
Breaking a Greedy Algorithm
To distinguish (1) & (2): Find example where the two algorithms
produce different outputs. (At least one will be incorrect.)
Example:
l1 = 5, w1 = 3 (longer ratio)
l1 = 2, w1 = 1 (larger difference)
Alg#1: #2 #1 → 1 · 2 + 3 · 7 = 23
Alg#2: #1 #2 → 3 · 5 + 1 · 7 = 22
Tim Roughgarden
The Story So Far
So: Alg#1 not (always) correct.
Tim Roughgarden