Lecture 01 - Introduction To Algorithms
Lecture 01 - Introduction To Algorithms
Solving
Lecture 01 – Introduction to
Algorithms
problem
algorithm
for i=1 to n
swap a[i] with smallest of a[i],…,a[n]
Basic Issues Related to
Algorithms
• How to design algorithms
• How to express algorithms
• Proving correctness
• Efficiency (or complexity) analysis
• Theoretical analysis
• Empirical analysis
• Optimality
Algorithm design
strategies
• Brute force • Greedy approach
• Transform and
conquer • Space and time
tradeoffs
Good Algorithm
• How good is the algorithm?
• Correctness
• Time efficiency
• Space efficiency
• Does there exist a better algorithm?
• Lower bounds
• Optimality
Euclid’s Algorithm
• Problem: Find gcd(m,n), the greatest common
divisor of two nonnegative, not both zero integers
m and n
• Examples:
• gcd(60,24) = 12, gcd(60,0) = 60, gcd(0,0) = ?
• Euclid’s algorithm is based on repeated application
of equality
• gcd(m,n) = gcd(n, m mod n)
• until the second number becomes 0, which makes
the problem trivial.
• Example:
• gcd(60,24) = gcd(24,12) = gcd(12,0) = 12
Two descriptions of Euclid’s
algorithm
Two Method to express algorithm
• Algorithm Description
• Step 1 If n = 0, return m and stop; otherwise go to Step
2
• Step 2 Divide m by n and assign the value of the
remainder to r
• Step 3 Assign the value of n to m and the value of r to n.
Go to Step 1.
• Pseudo code:
while n ≠ 0 do
r ← m mod n
m← n
n ← r
return m
Other methods for
computing gcd(m,n)
• Middle-school procedure
• Step 1 Find the prime factorization of m
• Step 2 Find the prime factorization of n
• Step 3 Find all the common prime factors
• Step 4 Compute the product of all the
common prime factors and return it as
gcd(m,n)
• Is this an algorithm? How efficient is it?
Sieve of Eratosthenes
Input: Integer n ≥ 2
Output: List of primes less than or equal to n
for p ← 2 to n do A[p] ← p
for p ← 2 to n do
if A[p] ≠ 0
//p hasn’t been previously eliminated from
the list
j ← p* p
while j ≤ n do
A[j] ← 0 //mark element as eliminated
Example: j←j+p
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
END!