Introduction To Algorithms
Introduction To Algorithms
• What is an Algorithm
• Steps in Designing and Implementing an
Algorithm
• Important Problem Types
ALGORITHM
• A sequence of unambiguous
instructions for solving a problem,
i.e. for obtaining the required output
for any legitimate input in a finite
amount of time
What is an algorithm?
An algorithm is a sequence of unambiguous instructions
for solving a problem, i.e., for obtaining a required
output for any legitimate input in a finite amount of
time.
problem
algorithm
algorithm
algorithmic solution
(different from a conventional solution)
Understand the problem
Design an algorithm
Prove correctness
while n ≠ 0 do
r ← m mod n
m← n
n←r
return m
Other methods for computing gcd(m,n)
Consecutive integer checking algorithm
Step 1 Assign the value of min{m,n} to t
Step 2 Divide m by t. If the remainder is 0, go to
Step 3;
otherwise, go to Step 4
Step 3 Divide n by t. If the remainder is 0, return
t and stop;
otherwise, go to Step 4
Step 4 Decrease t by 1 and go to Step 2
Is this slower than Euclid’s algorithm? How much
slower? O(n), if n <= m , vs O(log n)
Other methods for gcd(m,n) [cont.]
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?
i←j-1
while i > 0 and A[i] > key
do A[i + 1] ← A[i]
i←i–1
A[i + 1] ← key
Invariant: at the start of the for loop the elements in A[1 . . j-1] are in
sorted order
19
Proving Loop Invariants
• Proving loop invariants works like induction
• Initialization (base case):
– It is true prior to the first iteration of the loop
• Maintenance (inductive step):
– If it is true before an iteration of the loop, it remains true before the
next iteration
• Termination:
– When the loop terminates, the invariant gives us a useful property
that helps show that the algorithm is correct
– Stop the induction when the loop terminates
20
Loop Invariant for Insertion Sort
• Initialization:
– Just before the first iteration, j =
2:
the subarray A[1 . . j-1] = A[1],
(the element originally in A[1]) –
is sorted
21
Loop Invariant for Insertion Sort
• Maintenance:
– the while inner loop moves A[j -1], A[j -2], A[j
-3], and so on, by one position to the right until
the proper position for key (which has the value
that started out in A[j]) is found
– At that point, the value of key is placed into this
position.
22
Loop Invariant for Insertion Sort
• Termination:
– The outer for loop ends when j = n + 1 j-1 = n
– Replace n with j-1 in the loop invariant:
• the subarray A[1 . . n] consists of the elements
originally in A[1 . . n], but in sorted orderj - 1 j