Introduction to Algorithms Rabie A Ramadan rabierabieramadan org
Introduction to Algorithms Rabie A. Ramadan rabie@rabieramadan. org http: //www. rabieramadan. org 7
Chapter 5 Decrease-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.
Decrease-and-Conquer 1. 2. 3. l l Reduce problem instance to smaller instance of the same problem Solve smaller instance Extend solution of smaller instance to obtain solution to original instance Can be implemented either top-down or bottomup Also referred to as inductive or incremental approach
3 Types of Decrease and Conquer l Decrease by a constant (usually by 1): • insertion sort • graph traversal algorithms (DFS and BFS) • topological sorting • algorithms for generating permutations, subsets l Decrease by a constant factor (usually by half) • binary search and bisection method • exponentiation by squaring • multiplication à la russe l Variable-size decrease • Euclid’s algorithm • selection by partition • Nim-like games This usually results in a recursive algorithm.
What’s the difference? Consider the problem of exponentiation: Compute xn l Brute Force: l Divide and conquer: l Decrease by one: l Decrease by constant factor: n-1 multiplications T(n) = 2*T(n/2) + 1 = n-1 T(n) = T(n-1) + 1 = n-1 T(n) = T(n/a) + a-1 = (a-1) n = when a = 2
Insertion Sort To sort array A[0. . n-1], sort A[0. . n-2] recursively and then insert A[n-1] in its proper place among the sorted A[0. . n-2] l Usually implemented bottom up (nonrecursively) Example: Sort 6, 4, 1, 8, 5 6|4 1 8 5 4 6|1 8 5 1 4 6|8 5 1 4 6 8|5 1 4 5 6 8
Pseudocode of Insertion Sort
Analysis of Insertion Sort l Time efficiency Cworst(n) = n(n-1)/2 Θ(n 2) Cbest(n) = n - 1 Θ(n) (also fast on almost sorted arrays) l Space efficiency: in-place l Best elementary sorting algorithm overall
Graph Traversal
Graph Traversal Many problems require processing all graph vertices (and edges) in systematic fashion Graph traversal algorithms: • Depth-first search (DFS) • Breadth-first search (BFS)
11
Decrease by One Depth-First Search: (Brave Traversal) l. Visits graph’s vertices by always moving away from last visited vertex to an unvisited one, backtracks if no adjacent unvisited vertex is available. l Recursive or it uses a stack • a vertex is pushed onto the stack when it’s reached for the first time • a vertex is popped off the stack when it becomes a dead end, i. e. , when there is no adjacent unvisited vertex l “Redraws” graph in tree-like fashion (with tree edges and back edges for undirected graph)
Group Activity Write an Algorithm for DFS?
Example: DFS traversal of undirected graph a b c d e f g h DFS tree: a ab abfe abf ab abgcdh abgcd … DFS traversal stack: 1 2 6 7 a b c d e f g h 4 3 5 8 Red edges are tree edges and other edges are back edges.
Notes on DFS l DFS can be implemented with graphs represented as: • adjacency matrices: Θ(|V|2). Why? • adjacency lists: Θ(|V|+|E|). Why? l Yields two distinct ordering of vertices: • order in which vertices are first encountered (pushed onto stack) • order in which vertices become dead-ends (popped off stack) l Applications: • checking connectivity, finding connected components • checking acyclicity (if no back edges)
Breadth First Search
Breadth First Search l Visits graph vertices by moving across to all the neighbors of the last visited vertex l Instead of a stack, BFS uses a queue l Similar to level-by-level tree traversal l “Redraws” graph in tree-like fashion (with tree edges and cross edges for undirected graph)
Group Activity Write an Algorithm for BFS Using a queue?
Example of BFS traversal of undirected graph a b c d e f g h BFS tree: a bef efg fg g ch hd d BFS traversal queue: 1 2 6 8 a b c d e f g h 3 4 5 7 Red edges are tree edges and white edges are cross edges.
Notes on BFS l BFS has same efficiency as DFS and can be implemented with graphs represented as: • adjacency matrices: Θ(|V|2). Why? • adjacency lists: Θ(|V|+|E|). Why? l Yields single ordering of vertices (order added/deleted from queue is the same) l Applications: same as DFS, but can also find paths from a vertex to all other vertices with the smallest number of edges
DAGs and Topological Sorting A dag: a directed acyclic graph, i. e. a directed graph with no (directed) cycles a b a dag not a dag c d Vertices of a dag can be linearly ordered so that for every edge its starting vertex is listed before its ending vertex (topological sorting). Being a dag is also a necessary condition for topological sorting to be possible.
Digraph - Example l l l A part-time student needs to take a set of five courses {C 1, C 2, C 3, C 4, C 5}, only one course per term, in any order as long as the following course prerequisites are met: • • l C 1 and C 2 have no prerequisites C 3 requires C 1 and C 2 C 4 requires C 3 C 5 requires C 3 and C 4. The situation can be modeled by a diagraph: • • Vertices represent courses. Directed edges indicate prerequisite requirements. Vertices of a dag can be linearly ordered so that for every edge its starting vertex is listed before its ending vertex (topological sorting). Being a dag is also a necessary condition for topological sorting to be possible.
Topological Sorting Example Order the following items in a food chain tiger human fish sheep shrimp plankton wheat
Solving Topological Sorting Problem l l l Solution: Verify whether a given digraph is a dag and, if it is, produce an ordering of vertices. Two algorithms for solving the problem. They may give different (alternative) solutions. DFS-based algorithm • Perform DFS traversal and note the order in which vertices become dead ends (that is, are popped of the traversal stack). • Reversing this order yields the desired solution, provided that no back edge has been encountered during the traversal.
Example Complexity: as DFS
Solving Topological Sorting Problem l Source removal algorithm • Identify a source, which is a vertex with no incoming edges and delete it along with all edges outgoing from it. • There must be at least one source to have the problem solved. • Repeat this process in a remaining diagraph. • The order in which the vertices are deleted yields the desired solution.
Example
Source removal algorithm Efficiency: same as efficiency of the DFS-based algorithm, but how would you identify a source? “Invert” the adjacency lists for each vertex to count the number of incoming edges by going thru each adjacency list and counting the number of times that each vertex appears in these lists.
Decrease-by-Constant-Factor Algorithms In this variation of decrease-and-conquer, instance size is reduced by the same factor (typically, 2) Examples: • Binary search and the method of bisection • Exponentiation by squaring • Multiplication à la russe (Russian peasant method) • Fake-coin puzzle • Josephus problem
Exponentiation by Squaring The problem: Compute an where n is a nonnegative integer The problem can be solved by applying recursively the formulas: For even values of n a n = (a n/2 )2 if n > 0 and a 0 = 1 For odd values of n n-1)/2 )2 a a n = (a (n-1)/2 Recurrence: M(n) = M( n/2 ) + f(n), where f(n) = 1 or 2, M(0) = 0 Master Theorem: M(n) Θ(log n)
Russian Peasant Multiplication The problem: Compute the product of two positive integers Can be solved by a decrease-by-half algorithm based on the following formulas. For even values of n: n*m = n * 2 m 2 For odd values of n: n * m = n – 1 * 2 m + m if n > 1 and m if n = 1 2
Example of Russian Peasant Multiplication Compute 20 * 26 n m 20 26 10 52 5 104 2 208 1 416 104 + 416 520
Fake-Coin Puzzle (simpler version) There are n identically looking coins one of which is fake. There is a balance scale but there are no weights; the scale can tell whether two sets of coins weigh the same and, if not, which of the two sets is heavier (but not by how much, i. e. 3 -way comparison). Design an efficient algorithm for detecting the fake coin. Assume that the fake coin is known to be lighter than the genuine ones. - Divide them into two piles , put them into the scale , neglect the heavier one. Repeat Decrease by factor 2 algorithm What about odd n? T(n) = log n Decrease by factor 3 algorithm (Q 3 on page 187 of Levitin) T(n)
- Slides: 33