2 - Types of Algorithms
2 - Types of Algorithms
2nd edition
— http://www.mif.vu.lt/~valdas/ALGORITMAI/LITERATURA/Cormen/Cormen.pdf
Lecture Notes
●
— http://www.cis.upenn.edu/~matuszek/cit594-2014/
2
Learning Outcomes
algorithms
3
What is an algorithm?
problem
algorithm
4
What are algorithms used for?
●Example
●Example
●Example
5
Properties of algorithms
6
Algorithm Correctness
problems
7
Are the following algorithms?
Shampoo instructions
● Cooking recipe
●
— “Lather. Rinse. Repeat.” — “Stir-fry until crisp-tender.”
8
Are the following algorithms?
9
Is the following an algorithm?
●Long division
14
●58 / 4 4 58
= 14 + remainder 2 4
18
16
2
10
Example of algorithm
E.g. given the input sequence {31, 41, 59, 26, 41, 58}, a sorting
●
algorithm returns as output the sequence {26, 31, 41, 41, 58, 59}.
●Many methods to solve these biological problems use ideas from several of
the topics to be discussed in this module, thereby enabling scientists to
accomplish tasks while using resources efficiently.
●The savings are in time, both human and machine, and in money, as more
information can be extracted from data produced by laboratory techniques.
12
Other computational problems:
The Internet
●The Internet enables people all around the world to quickly access and
retrieve large amounts of information.
With the aid of clever algorithms, sites on the Internet are able to manage and
●
13
Other computational problems:
E-commerce
●Electronic commerce enables goods and services to be negotiated and
exchanged electronically, and it depends on the privacy of personal
information such as credit card numbers, passwords, and bank statements.
14
Other computational problems:
Manufacturing and other commercial applications
●Manufacturing and other commercial enterprises often need to allocate scarce
resources in the most beneficial way.
— An oil company may wish to know where to place its wells in order to
maximize its expected profit.
— A political candidate may want to determine where to spend money
buying campaign advertising in order to maximize the chances of
winning an election.
— An airline may wish to assign crews to flights in the least expensive way
possible, making sure that each flight is covered and that government
regulations regarding crew scheduling are met.
— An Internet service provider may wish to determine where to place
additional resources in order to serve its customers more effectively.
All of these are examples of problems that can be solved using linear
●
programming.
15
Describing Algorithms
16
Programs VERSUS Algorithms
programming language
Many programs can exist for the same algorithm
●
17
Problem, Algorithm and Program
Problem problem
Given n, find n!
Algorithm algorithm
If n = 0, n! = 1
Else n! = n * (n – 1)!
Program in Java
public long factorial(int n) { input computer output
if(n == 0) return 1; program
else return n * factorial(n – 1);
}
18
Activity – Greatest Common Divisor
●The first algorithm “invented” in history was Euclid’s algorithm for finding
the greatest common divisor (GCD) of two natural numbers
●Definition: The GCD of two numbers, when at least one of them is not
zero, is the largest positive integer that divides the numbers without a
remainder.
● For example, the GCD of 8 and 12 is 4.
19
Activity – Greatest Common Divisor
20
Activity – Greatest Common Divisor
21
Activity – Greatest Common Divisor
public int gcd(int x, int y) {
while (y!=0) {
int temp = x%y;
x = y;
y = temp;
}
return x;
}
GCD(72, 120)
temp x y
After 0 rounds -- 72 120
After 1 round 72 120 72
After 2 rounds 48 72 48
After 3 rounds 24 48 24
After 4 rounds 0 24 0
Output: 24
22
Algorithm classification
grouped together
This classification scheme is neither exhaustive nor disjoint
●
23
Recursive Dynamic Progr. Brute-Force Randomized
24
Recursive Dynamic Progr. Brute-Force Randomized
25
Recursive Dynamic Progr. Brute-Force Randomized
26
Recursive Dynamic Progr. Brute-Force Randomized
27
Recursive Dynamic Progr. Brute-Force Randomized
28
Recursive Dynamic Progr. Brute-Force Randomized
Why recursion?
Usually recursive algorithms have less code, therefore algorithms can
●
29
Recursive Dynamic Progr. Brute-Force Randomized
Why recursion?
Some recursive algorithms are more efficient than equivalent iterative
●
algorithms.
Example, each of the following recursive power methods evaluate xn
●
long product = 1;
product *= x
return product;
30
Recursive Dynamic Progr. Brute-Force Randomized
Why recursion?
// recursive
if (n==1)
return x;
if (n==0)
return 1;
return t*t;
return x*t*t;
}
31
Recursive Dynamic Progr. Brute-Force Randomized
Backtracking
●Suppose you have to make a series of decisions, among various
choices, where
—You don’t have enough information to know what to choose
choices:
—Go straight
—Go left
—Go right
solution
●Many types of maze problem can be solved with backtracking
Recursive Dynamic Progr. Brute-Force Randomized
Backtracking algorithms
algorithms.
34
Recursive Dynamic Progr. Brute-Force Randomized
35
Recursive Dynamic Progr. Brute-Force Randomized
36
Recursive Dynamic Progr. Brute-Force Randomized
● A backtracking algorithm:
— Tests to see if a solution has been found, and if so, return it;
otherwise
‣ For each choice that can be made at this point,
* Make that choice
* Recur
* If the recursion returns a solution, return it
‣ If no choices remain, return failure
37
Recursive Dynamic Progr. Brute-Force Randomized
Internal nodes
Leaf nodes
Recursive Dynamic Progr. Brute-Force Randomized
Depth-First Search
●Depth-First Traversal:
— Preorder traversal
— Inorder traversal (for binary trees only)
— Postorder traversal
39
Recursive Dynamic Progr. Brute-Force Randomized
Depth-First Search
40
Easy representation: draw a red line around the ordered rooted tree
starting at the root, moving along the edges
Preorder: listing each vertex the first time this line passes it
Inorder: listing a leaf the first time the line passes it and listing
each internal vertex the second time the line passes it
Postorder: listing a vertex the last time it is passed on the way back up
to its parent
in order: h d b i e j a f c k g
preorder:a b d h e i j c f g k
post order:h d i j e b f k g c a
Recursive Dynamic Progr. Brute-Force Randomized
N-L-R
H
D L
B F J N
A C E G I K M O
H D B A C F E G L J I K N M O
41
Recursive Dynamic Progr. Brute-Force Randomized
L-N-R
H
D L
B F J N
A C E G I K M O
A B C D E F G H I J K L M N O
Note: An inorder traversal of a BST visits the keys sorted in increasing order.
42
Recursive Dynamic Progr. Brute-Force Randomized
D L
B F J N
A C E G I K M O
A C B E G F D I K J M O N L H
43
Recursive Dynamic Progr. Brute-Force Randomized
Solving a maze
●Consider a maze, shown in the diagram above, where a player has to
44
Recursive Dynamic Progr. Brute-Force Randomized
Maze Solved!!!
Dead End
Dead End
Dead End
45
Recursive Dynamic Progr. Brute-Force Randomized
Divide-and-Conquer
46
Recursive Dynamic Progr. Brute-Force Randomized
Divide-and-Conquer (contd)
● Approach
47
Recursive Dynamic Progr. Brute-Force Randomized
Divide-and-Conquer (contd)
Problem of size n
Sub-problem 1 Sub-problem 2
of size n/2 of size n/2
Solution to Solution to
sub-problem 1 sub-problem 2
Solution to
original problem
Note:
● Divide and conquer algorithms often implemented using recursion
● But, not all recursive functions are divide-and-conquer algorithms
48
Recursive Dynamic Progr. Brute-Force Randomized
●Otherwise
49
Recursive Dynamic Progr. Brute-Force Randomized
● Quicksort:
— Partition the array into two parts (smaller numbers in one part,
larger numbers in the other part)
● Mergesort:
50
Recursive Dynamic Progr. Brute-Force Randomized
Dynamic Programming
sub-problems.
●Unlike divide and conquer, sub-problems are not independent.
51
Recursive Dynamic Progr. Brute-Force Randomized
● Approach
— Divide problem into smaller subproblems
‣ Sub-problems must be of same type
‣ Sub-problems must overlap
— Solve each sub-problem recursively
‣ May simply look up solution
— Combine solutions to solve original problem
— Store solution to problem
52
Recursive Dynamic Progr. Brute-Force Randomized
● Fibonacci numbers
— fibonacci(0) = 1
— fibonacci(1) = 1
— fibonacci(n) = fibonacci(n-1) + fibonacci(n-2)
● Recursive algorithm to calculate fibonacci(n)
— If n is 0 or 1, return 1
— Else compute fibonacci(n-1) and fibonacci(n-2)
— Return their sum
● Simple algorithm BUT
n
— Exponential time O(2 ) Very time-consuming!
53
Recursive Dynamic Progr. Brute-Force Randomized
Fib(5)
+
Fib(4) Fib(3)
+ +
Fib(1) Fib(0)
54
Recursive Dynamic Progr. Brute-Force Randomized
55
Recursive Dynamic Progr. Brute-Force Randomized
Greedy algorithms
consequences
—You hope that by choosing a local optimum at each step, you will end
up at a global optimum
56
Recursive Dynamic Progr. Brute-Force Randomized
●Suppose you want to count out a certain amount of money, using the
fewest possible bills and coins. A greedy algorithm would do this would
be:
●At each step, take the largest possible bill or coin that does not
overshoot
—Example: To make $6.39, you can choose:
‣a $5 bill
‣a $1 bill, to make $6
‣a 25¢ coin, to make $6.25
‣A 10¢ coin, to make $6.35
‣four 1¢ coins, to make $6.39
●For US money, the greedy algorithm always gives the optimum solution
57
Recursive Dynamic Progr. Brute-Force Randomized
58
Recursive Dynamic Progr. Brute-Force Randomized
A scheduling problem
●You have to run nine jobs, with running times of 3, 5, 6, 10, 11, 14, 15,
18, and 20 minutes
●You have three processors on which you can run these jobs
is available
P1 20 10 3
P2 18 11 6
P3 15 14 5
59
Recursive Dynamic Progr. Brute-Force Randomized
Another approach
●What would be the result if you ran the shortest job first?
●Again, the running times are 3, 5, 6, 10, 11, 14, 15, 18, and 20 minutes
P1 3 10 15
P2 5 11 18
P3 6 14 20
60
Recursive Dynamic Progr. Brute-Force Randomized
An optimum solution
P1 20 14
P2
18 11 5
P3
15 10 6 3
61
Recursive Dynamic Progr. Brute-Force Randomized
Traveling salesman
●A salesman must visit every city (starting from city A), and wants to
cover the least possible distance
—He can revisit a city (and reuse a road) if necessary
●He does this by using a greedy algorithm: He goes to the next nearest
A 2 B 4 C ●From A he goes to B
●From B he goes to D
ABDBCE, at a cost of 16
D ●An actual least-cost path from A is
E ADBCE, at a cost of 14
62
Recursive Dynamic Progr. Brute-Force Randomized
problem
● At each node, apply the bounding methods
— If the bounds match, it is deemed a feasible solution to that
particular subproblem
— If bounds do not match, partition the problem represented by that
node, and make the two subproblems into children nodes
●Continue, using the best known feasible solution to trim sections of the
tree, until all nodes have been solved or trimmed
63
Recursive Dynamic Progr. Brute-Force Randomized
64
Recursive Dynamic Progr. Brute-Force Randomized
Brute-force Algorithm
65
Recursive Dynamic Progr. Brute-Force Randomized
Generate
Filter Solutions
Candidates
Trash
66
Recursive Dynamic Progr. Brute-Force Randomized
67
Recursive Dynamic Progr. Brute-Force Randomized
68
Recursive Dynamic Progr. Brute-Force Randomized
Heuristic Algorithm
●The term heuristic is used for algorithms which find solutions among all
possible ones, but they do not guarantee that the best will be found, therefore
they may be considered as approximate and not accurate algorithms.
●Heuristic algorithms
— Approach
●These algorithms, usually find a solution close to the best one and they
find it fast and easily.
●Sometimes these algorithms can be accurate, that is they actually find
the best solution, but the algorithm is still called heuristic until this best
solution is proven to be the best.
The method used from a heuristic algorithm is one of the known
●
70
Recursive Dynamic Progr. Brute-Force Randomized
71
Recursive Dynamic Progr. Brute-Force Randomized
Randomized algorithms
● Related topics
72
Recursive Dynamic Progr. Brute-Force Randomized
Randomized algorithms
73
Recursive Dynamic Progr. Brute-Force Randomized
Pseudo-random numbers
74
Recursive Dynamic Progr. Brute-Force Randomized
— If you start over with the same seed, you get the same sequence of
“random” numbers
●There are complex mathematical tests for “randomness” which you should
know if you want to “roll your own”
75
Recursive Dynamic Progr. Brute-Force Randomized