Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Algorithms

Similar presentations


Presentation on theme: "Introduction to Algorithms"— Presentation transcript:

1 Introduction to Algorithms
Rabie A. Ramadan rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials

2 The problem is to find the convex hull of the points or the polygon.
The First Problem Convex Hull The problem is to find the convex hull of the points or the polygon. That is, a polygonal area that is of smallest length and so that any pair of points within the area have the line segment between them contained entirely inside the area.

3 Convex Hull Given a set of pins on a pinboard
And a rubber band around them How does the rubber band look when it snaps tight? We represent the convex hull as the sequence of points on the convex hull polygon, in counter-clockwise order. 2 1 3 4 6 5

4 Brute force Solution Based on the following observation:
A line segment connecting two points Pi and Pj of a set on n points is a part of the convex hull’s boundary if and only if all the other points of the set lie on the same side of the straight line through these two points. We need to try every pair of points  O(n3 )

5 Quickhull Algorithm Convex hull: smallest convex set that includes given points. Assume points are sorted by x-coordinate values Identify extreme points P1 and P2 (leftmost and rightmost) Compute upper hull recursively: find point Pmax that is farthest away from line P1P2 compute the upper hull of the points to the left of line P1Pmax compute the upper hull of the points to the left of line PmaxP2 Compute lower hull in a similar manner Pmax P2 P1

6 QuickHull Algorithm How to find the Pmax point
Pmax maximizes the area of the triangle PmaxP1P2 if tie, select the Pmax that maximizes the angle PmaxP1P2 The points inside triangle PmaxP1P2 can be excluded from further consideration Worst case (almost like quick sort) : O(n2) Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. The steps are: Pick an element, called a pivot, from the list. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. The base case of the recursion are lists of size zero or one, which never need to be sorted.

7 QuickHull Could you Solve the Quick Hull Problem in O(nlogn) ?
Quicksort is a divide and conquer algorithm. Quicksort first divides a large list into two smaller sub-lists: the low elements and the high elements. Quicksort can then recursively sort the sub-lists. The steps are: Pick an element, called a pivot, from the list. Reorder the list so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. Recursively sort the sub-list of lesser elements and the sub-list of greater elements. The base case of the recursion are lists of size zero or one, which never need to be sorted.

8 Convex Hull: Divide & Conquer
Preprocessing: sort the points by x-coordinate Divide the set of points into two sets A and B: A contains the left n/2 points, B contains the right n/2 points Recursively compute the convex hull of A Recursively compute the convex hull of B Merge the two convex hulls A B

9 Convex Hull: Runtime Preprocessing: sort the points by x-coordinate
Divide the set of points into two sets A and B: A contains the left n/2 points, B contains the right n/2 points Recursively compute the convex hull of A Recursively compute the convex hull of B Merge the two convex hulls O(n log n) just once O(1) T(n/2) T(n/2) O(n)

10 Convex Hull: Runtime T(n) = 2 T(n/2) + n Solves to T(n) = (n log n)
Runtime Recurrence: T(n) = 2 T(n/2) + n Solves to T(n) = (n log n)

11 Merging in O(n) time Find upper and lower tangents in O(n) time
4 Find upper and lower tangents in O(n) time Compute the convex hull of AB: Walk clockwise around the convex hull of A, starting with left endpoint of lower tangent When hitting the left endpoint of the upper tangent, cross over to the convex hull of B Walk counterclockwise around the convex hull of B When hitting right endpoint of the lower tangent we’re done This takes O(n) time 5 3 6 2 1 7 A B

12 QuickHull How to find the upper and lower tangents in O(n) time?

13 Finding the lower tangent in O(n) time
3 a = rightmost point of A b = leftmost point of B while T=ab not lower tangent to both convex hulls of A and B do{ while T not lower tangent to convex hull of A do{ a=a } while T not lower tangent to convex hull of B do{ b=b } } 4 4=b 2 3 5 5 a=2 6 1 7 1 can be checked in constant time How? Check only A+1 and A-1 for instance Note that to determine if some line, T = AB, is a lower tangent to the left hull you only need to check the 2 points on either side of point A (A-1 and A+1). If both these points are above the line T then all the points in the left hull are above the line T. That result comes from the fact that the hulls are convex. Note that you have to be careful about accessing the A-1 and A+1 elements so you don’t go out of the array bounds. A B T is lower tangent if all the points are above the line

14 Convex Hull – Divide & Conquer
Split set into two, compute convex hull of both, combine. Convex Hull – Divide & Conquer

15 Convex Hull – Divide & Conquer
Split set into two, compute convex hull of both, combine. Convex Hull – Divide & Conquer

16 Split set into two, compute convex hull of both, combine.

17 Split set into two, compute convex hull of both, combine.

18 Split set into two, compute convex hull of both, combine.

19 Split set into two, compute convex hull of both, combine.

20 Split set into two, compute convex hull of both, combine.

21 Split set into two, compute convex hull of both, combine.

22 Split set into two, compute convex hull of both, combine.

23 Split set into two, compute convex hull of both, combine.

24 Split set into two, compute convex hull of both, combine.

25 Merging two convex hulls.

26 Merging two convex hulls: (i) Find the lower tangent.

27 Merging two convex hulls: (i) Find the lower tangent.

28 Merging two convex hulls: (i) Find the lower tangent.

29 Merging two convex hulls: (i) Find the lower tangent.

30 Merging two convex hulls: (i) Find the lower tangent.

31 Merging two convex hulls: (i) Find the lower tangent.

32 Merging two convex hulls: (i) Find the lower tangent.

33 Merging two convex hulls: (i) Find the lower tangent.

34 Merging two convex hulls: (i) Find the lower tangent.

35 Merging two convex hulls: (ii) Find the upper tangent.

36 Merging two convex hulls: (ii) Find the upper tangent.

37 Merging two convex hulls: (ii) Find the upper tangent.

38 Merging two convex hulls: (ii) Find the upper tangent.

39 Merging two convex hulls: (ii) Find the upper tangent.

40 Merging two convex hulls: (ii) Find the upper tangent.

41 Merging two convex hulls: (ii) Find the upper tangent.

42 Merging two convex hulls: (iii) Eliminate non-hull edges.

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

44 Decrease-and-Conquer
Reduce problem instance to smaller instance of the same problem Solve smaller instance Extend solution of smaller instance to obtain solution to original instance Also referred to as inductive or incremental approach

45 3 Types of Decrease and Conquer
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.

46 What is the difference? Consider the problem of exponentiation: Compute an 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 Try to get the students involved in coming up with these: Brute Force: an= a*a*a*a*...*a n Divide and conquer: an= an/2 * an/2 (more accurately, an= an/2 * a n/2│) Decrease by one: an= an-1* a (one hopes a student will ask what is the difference with brute force here: there is none in the resulting algorithm, of course, but you can arrive at it in two different ways) Decrease by constant factor: an= (an/2) (again, if no student asks about it, be sure to point out the difference with divide and conquer. Here there is a significant difference that leads to a much more efficient algorithm – in divide and conquer we recompute an/2 T(n) = T(n/a) + a-1 = (a-1) n = when a = 2

47 What is the difference? Consider the problem of exponentiation: Compute an Brute Force: an= a*a*a*a*...*a Divide and conquer: an= an/2 * an/2 (more accurately, an= an/2 * a n/2│) Decrease by one:- (the same as the brute force algorithm) an= an-1* a Decrease by constant factor: (more faster than divide and conquer ) an= (an/2)2 Try to get the students involved in coming up with these: Brute Force: an= a*a*a*a*...*a n Divide and conquer: an= an/2 * an/2 (more accurately, an= an/2 * a n/2│) Decrease by one: an= an-1* a (one hopes a student will ask what is the difference with brute force here: there is none in the resulting algorithm, of course, but you can arrive at it in two different ways) Decrease by constant factor: an= (an/2) (again, if no student asks about it, be sure to point out the difference with divide and conquer. Here there is a significant difference that leads to a much more efficient algorithm – in divide and conquer we recompute an/2

48 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) (Video) Example: Sort 6, 4, 1, 8, | 4 6 | | 8 5 | 5

49 Write a Pseudocode for Insertion Sort

50 Analysis of Insertion Sort
Time efficiency Cworst(n) = n(n-1)/2  Θ(n2) Cbest(n) = n - 1  Θ(n) (also fast on almost sorted arrays) Space efficiency: in-place Best elementary sorting algorithm overall

51 The problems Our eyes can pick out the connected components of an undirected graph by just looking at a picture of the graph, but it is much harder to do it with a glance at the adjacency lists. Detecting cycle in a graph Topological Sorting Sudoku Puzzles To test if a graph is bipartite What is a bipartite graph?

52 What is a bipartite graph?
A bipartite graph (or bigraph) is a graph whose vertices can be divided into two disjoint sets U and V such that every edge connects a vertex in U to one in V; that is, U and V are independent sets.

53 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)

54 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 Using 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 Try to do it yourself and show me your trail in the following example?

55 Group Activity Write an Algorithm for DFS?

56 Example: DFS traversal of undirected graph
b e f c d g h abgcdh abgcd abgc abfe abg abf ab a DFS tree: DFS traversal stack: 1 2 6 7 Traversal using alphabetical order of vertices. Work through this example in detail, showing the traversal by highlighting edges on the graph and showing how the stack evolves: 8 h 3 7 d stack shown growing upwards 4 e c number on left is order that vertex was pushed onto stack 3 f g number on right is order that vertex was popped from stack 2 b overlap is because after e, f are popped off stack, g and c 1 a are pushed onto stack in their former locations. order pushed onto stack: a b f e g c d h order popped from stack: e f h d c g b a * show dfs tree as it gets constructed, back edges a b c d Red edges are tree edges and other edges are back edges. e f g h 4 3 5 8

57 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)

58 The Problem Finding paths from a vertex to all other vertices with the smallest number of edges

59 Breadth First Search 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.

60 Example of BFS traversal of undirected graph
bef efg hd fg ch a g d BFS tree: BFS traversal queue: 1 2 6 8 a b c d Red edges are tree edges and white edges are cross edges. e f g h 3 4 5 7

61 Write an Algorithm for BFS Using a queue?

62 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

63 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.

64 Topological Sorting Example
Order the following items in a food chain tiger human fish sheep shrimp plankton wheat

65 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.

66 Example Complexity: as DFS

67 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.

68 Example

69 Source removal algorithm Efficiency
Efficiency: same as efficiency of the DFS-based algorithm

70 Decrease-by-Constant-Factor Algorithms
In this variation of decrease-and-conquer, instance size is reduced by the same factor (typically, 2) The Problems : Binary search and the method of bisection Exponentiation by squaring Multiplication à la russe (Russian peasant method) Fake-coin puzzle Josephus problem

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

72 Example of Russian Peasant Multiplication
Compute 20 * 26 n m 520

73 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) (your assignment) T(n) = log n What about odd n? T(n)

74 Variable-Size-Decrease Algorithms
In the variable-size-decrease variation of decrease-and-conquer, instance size reduction varies from one iteration to another The Problems : Euclid’s algorithm for greatest common divisor Partition-based algorithm for selection problem Interpolation search Some algorithms on binary search trees Nim and Nim-like games

75 Euclid’s Algorithm Euclid’s algorithm is based on repeated application of equality gcd(m, n) = gcd(n, m mod n) Ex.: gcd(80,44) = gcd(44,36) = gcd(36, 12) = gcd(12,0) = 12 One can prove that the size, measured by the second number, decreases at least by half after two consecutive iterations. Hence, T(n)  O(log n)

76 Selection Problem Find the k-th smallest element in a list of n numbers k = 1 or k = n median: k = n/2 Example: 4, 1, 10, 9, 7, 12, 8, 2, 15  n =9 median = 9/2 = 5 The median is used in statistics as a measure of an average value of a sample. In fact, it is a better (more robust) indicator than the mean, which is used for the same purpose.

77 Algorithms for the Selection Problem
The sorting-based algorithm: Sort and return the k-th element Efficiency (if sorted by mergesort): Θ(nlog n) Can you find a faster algorithm? A faster algorithm is based on using the quicksort-like partition of the list. Let s be a split position obtained by a partition: Assuming that the list is indexed from 1 to n: If s = k, the problem is solved; if s > k, look for the k-th smallest elem. in the left part; if s < k, look for the (k-s)-th smallest elem. in the right part. Note: The algorithm can simply continue until s = k. s all are ≤ A[s] all are ≥ A[s]

78 Example 4, 1, 10, 9, 7, 12, 8, 2, 15 n= 9 median = n/2 = 5
So, find the 5th smallest item ? Select the pivot 4 4, 1, 10, 9, 7, 12, 8, 2, 15 2, 1, 4, 9, 7, 12, 8, 10, 15 since s=3 and k= 5 proceed with the right part , Select 9 as a pivot 9, 7, 12, 8, 10, 15 8, 7, 9, 12, 10, 15 Since s =6 and k=5 proceed with the left part , Select 8 as a pivot 8, 7 7 , 8 Now s=k=5 and the median is 8

79 Part of your assignment
Report the complexity of the previous algorithm?

80 Binary Search Tree Algorithms
Several algorithms on BST requires recursive processing of just one of its subtrees, e.g., Searching Insertion of a new key Finding the smallest (or the largest) key k <k >k

81 Searching in Binary Search Tree
Algorithm BTS(x, v) //Searches for node with key equal to v in BST rooted at node x if x = NIL return -1 else if v = K(x) return x else if v < K(x) return BTS(left(x), v) else return BTS(right(x), v) Efficiency worst case: C(n) = n

82 Chapter 6 Transform-and-Conquer
Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

83 Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance simplification) to a different representation of the same instance (representation change) to a different problem for which an algorithm is already available (problem reduction)

84 Instance simplification - Presorting
Solve a problem’s instance by transforming it into another simpler/easier instance of the same problem Presorting Many problems involving lists are easier when list is sorted. searching computing the median (selection problem) checking if all elements are distinct (element uniqueness) Also: Topological sorting helps solving some problems for dags. Presorting is used in many geometric algorithms.

85 How fast can we sort ? Efficiency of algorithms involving sorting depends on efficiency of sorting. Note: About nlog2 n comparisons are also sufficient to sort array of size n (by mergesort).

86 Searching with presorting
Problem: Search for a given K in A[0..n-1] Presorting-based algorithm: Stage 1 Sort the array by an efficient sorting algorithm Stage 2 Apply binary search Efficiency: Θ(nlog n) + O(log n) = Θ(nlog n) Good or bad? Why do we have our dictionaries, telephone directories, etc. sorted?

87 Element Uniqueness with presorting
Presorting-based algorithm Stage 1: sort by efficient sorting algorithm (e.g. mergesort) Stage 2: scan array to check pairs of adjacent elements Efficiency: Θ(nlog n) + O(n) = Θ(nlog n) Brute force algorithm Compare all pairs of elements Efficiency: O(n2)

88 Instance simplification – Gaussian Elimination
Given: A system of n linear equations in n unknowns with an arbitrary coefficient matrix. Transform to: An equivalent system of n linear equations in n unknowns with an upper triangular coefficient matrix. Solve the latter by substitutions starting with the last equation and moving up to the first one. a11x1 + a12x2 + … + a1nxn = b a11x1+ a12x2 + … + a1nxn = b1 a21x1 + a22x2 + … + a2nxn = b a22x2 + … + a2nxn = b2 an1x1 + an2x2 + … + annxn = bn annxn = bn

89 Gaussian Elimination (cont.)
The transformation is accomplished by a sequence of elementary operations on the system’s coefficient matrix (which don’t change the system’s solution): for i ←1 to n-1 do replace each of the subsequent rows (i.e., rows i+1, …, n) by a difference between that row and an appropriate multiple of the i-th row to make the new coefficient in the i-th column of that row 0

90 Example of Gaussian Elimination
Solve x1 - 4x2 + x3 = x1 - x x3 = x1 + x x3 = -3 Gaussian elimination row2 – (3/2)*row /2 2 row3 – (1/2)*row / row3–(3/5)*row2 /2 2 /5 -36/5 Backward substitution x3 = (-36/5) / (-6/5) = 6 x2 = (2+(1/2)*6) / 5 = 1 x1 = (6 – 6 + 4*1)/2 = 2

91 Pseudocode and Efficiency of Gaussian Elimination
Stage 1: Reduction to the upper-triangular matrix for i ← 1 to n-1 do for j ← i+1 to n do for k ← i to n+1 do A[j, k] ← A[j, k] - A[i, k] * A[j, i] / A[i, i] //improve! Stage 2: Backward substitution for j ← n downto 1 do t ← 0 for k ← j +1 to n do t ← t + A[j, k] * x[k] x[j] ← (A[j, n+1] - t) / A[j, j] Efficiency: Θ(n3) + Θ(n2) = Θ(n3) Read the Pseudocode code for the algorithm and find its efficiency?

92 Next we will continue chapters 6 , 9, and 10
It will be great if you can help me finish these chapters


Download ppt "Introduction to Algorithms"

Similar presentations


Ads by Google