Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 7.

Similar presentations


Presentation on theme: "Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 7."— Presentation transcript:

1 Introduction to Algorithms Rabie A. Ramadan rabie@rabieramadan.org http://www. rabieramadan.org 7

2 Chapter 5 Decrease-and-Conquer Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

3 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance to obtain solution to original instance Can be implemented either top-down or bottom- up Also referred to as inductive or incremental approach

4 3 Types of Decrease and Conquer Decrease by a constant (usually by 1): Decrease by a constant (usually by 1): insertion sort graph traversal algorithms (DFS and BFS) topological sorting algorithms for generating permutations, subsets Decrease by a constant factor (usually by half) binary search and bisection method exponentiation by squaring multiplication à la russe Variable-size decrease Euclid’s algorithm selection by partition Nim-like games This usually results in a recursive algorithm.

5 What’s the difference? Consider the problem of exponentiation: Compute x n Brute Force: Divide and conquer: Decrease by one: 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

6 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] 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

7 Pseudocode of Insertion Sort

8 Analysis of Insertion Sort Time efficiency C worst (n) = n(n-1)/2  Θ(n 2 ) C best (n) = n - 1  Θ(n) (also fast on almost sorted arrays) Space efficiency: in-place Best elementary sorting algorithm overall

9 Graph Traversal

10 Many problems require processing all graph vertices (and edges) in systematic fashion Graph traversal algorithms: Depth-first search (DFS) Breadth-first search (BFS)

11 11

12 Decrease by One Depth-First Search: (Brave Traversal) Visits graph’s vertices by always moving away from last visited vertex to an unvisited one, backtracks if no adjacent unvisited vertex is available. 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 “Redraws” graph in tree-like fashion (with tree edges and back edges for undirected graph)

13 Group Activity Write an Algorithm for DFS?

14 Example: DFS traversal of undirected graph ab ef cd gh DFS traversal stack: DFS tree: ab ef cd gh a ab abf abfe abf ab abg abgc abgcd abgcdh abgcd … Red edges are tree edges and other edges are back edges. 12 54 6 3 7 8

15 Notes on DFS DFS can be implemented with graphs represented as: adjacency matrices: Θ(|V| 2 ). Why? adjacency lists: Θ(|V|+|E|). Why? 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) Applications: checking connectivity, finding connected components checking acyclicity (if no back edges)

16 Breadth First Search

17 Visits graph vertices by moving across to all the neighbors of the last visited vertex Instead of a stack, BFS uses a queue Similar to level-by-level tree traversal “Redraws” graph in tree-like fashion (with tree edges and cross edges for undirected graph)

18 Group Activity Write an Algorithm for BFS Using a queue?

19 Example of BFS traversal of undirected graph BFS traversal queue: ab ef cd gh BFS tree: ab ef cd gh a bef efg fg g ch hd d Red edges are tree edges and white edges are cross edges. 1 3 26 475 8

20 Notes on BFS BFS has same efficiency as DFS and can be implemented with graphs represented as: adjacency matrices: Θ(|V| 2 ). Why? adjacency lists: Θ(|V|+|E|). Why? Yields single ordering of vertices (order added/deleted from queue is the same) Applications: same as DFS, but can also find paths from a vertex to all other vertices with the smallest number of edges

21 DAGs and Topological Sorting A dag: a directed acyclic graph, i.e. a directed graph with no (directed) cycles 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. ab cd ab cd a dag not a dag

22 Digraph - Example A part-time student needs to take a set of five courses {C1, C2, C3, C4, C5}, only one course per term, in any order as long as the following course prerequisites are met: C1 and C2 have no prerequisites C3 requires C1 and C2 C4 requires C3 C5 requires C3 and C4. 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.

23 Topological Sorting Example Order the following items in a food chain fish human shrimp sheep wheatplankton tiger

24 Solving Topological Sorting Problem 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.

25 Example Complexity: as DFS

26 Solving Topological Sorting Problem 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.

27 Example

28 Source removal algorithm Efficiency 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.

29 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

30 Exponentiation by Squaring The problem: Compute a n where n is a nonnegative integer The problem can be solved by applying recursively the formulas: For even values of n For odd values of n a n (a n/2 ) 2 if n > 0 and a 0 = 1 a n = (a n/2 ) 2 if n > 0 and a 0 = 1 a n (a (n-1)/2 ) 2 a a n = (a (n-1)/2 ) 2 a Recurrence: M(n) = M(  n/2  ) + f(n), where f(n) = 1 or 2, M(0) = 0 M(0) = 0 Master Theorem: M(n)  Θ(log n)

31 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: For odd values of n: n * m = * 2m n * m = * 2m + m if n > 1 and m if n = 1 n * m = * 2m + m if n > 1 and m if n = 1 n2n2n2n2 n – 1 2

32 Example of Russian Peasant Multiplication Compute 20 * 26 n m 20 26 10 52 5 104 104 2 208 + 1 416 416 520

33 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 Decrease by factor 3 algorithm (Q3 on page 187 of Levitin) T(n) = log n T(n) What about odd n?


Download ppt "Introduction to Algorithms Rabie A. Ramadan rabieramadan.org 7."

Similar presentations


Ads by Google