Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Recursive Algorithms. 2 Chapter Outline Analyzing recursive algorithms Recurrence relations Closest pair algorithms Convex hull algorithms Generating.

Similar presentations


Presentation on theme: "Chapter 2 Recursive Algorithms. 2 Chapter Outline Analyzing recursive algorithms Recurrence relations Closest pair algorithms Convex hull algorithms Generating."— Presentation transcript:

1 Chapter 2 Recursive Algorithms

2 2 Chapter Outline Analyzing recursive algorithms Recurrence relations Closest pair algorithms Convex hull algorithms Generating permutations Recursion and stacks

3 3 Prerequisites Before beginning this chapter, you should be able to: –Read and create recursive algorithms –Identify comparison and arithmetic operations –Use basic algebra

4 4 Goals At the end of this chapter you should be able to: –Create the recurrence relation for a recursive algorithm –Convert a simple recurrence relation into closed form –Explain the closest pair algorithm

5 5 Goals (continued) –Explain the convex hull algorithm –Generate permutations both recursively and iteratively –Explain the relationship between recursion and stacks

6 6 Recursive Algorithms Recursive algorithms solve the problem by solving smaller versions of the problem –If the smaller versions are only a little smaller, the algorithm can be called a reduce and conquer algorithm –If the smaller versions are about half the size of the original, the algorithm can be called a divide and conquer algorithm

7 7 Recursive Algorithm Analysis The analysis depends on –the preparation work to divide the input –the size of the smaller pieces –the number of recursive calls –the concluding work to combine the results of the recursive calls

8 8 Generic Recursive Algorithm Recurse( data, N, solution ) // data a set of input values // N the number of values in the set // solution the solution to this problem if N ≤ SizeLimit then DirectSolution( data, N, solution ) else DivideInput( data, N, smallerSets, smallerSizes, numberSmaller ) for i = 1 to numberSmaller do Recurse(smallerSets[i], smallerSizes[i], smallSolution[i]) end for CombineSolutions(smallSolution, numberSmaller, solution) end if

9 9 Generic Recursive Algorithm Analysis The recursive algorithm does the following amount of work: Where –DIR(N) is the amount of work done by the direct solution –DIV(N) is the amount of work done by the division of the problem –COM(N) is the amount of work done to combine the solutions

10 10 Divide and Conquer Example Largest( list, start, end ) if start ≥ end then return list[end] end if middle = (start + end) / 2 first = Largest( list, start, middle ) second = Largest( list, middle+1, end ) if first > second then return first else return second end if

11 11 Divide and Conquer Example Analysis This algorithm does: –One addition and division to calculate middle –Two recursive calls with lists about half the original size –One comparison to decide between the largest of the first half and the largest of the second half

12 12 Divide and Conquer Example Analysis The number of comparisons of list values done by this example is given by:

13 13 Recurrence Relation Form A recurrence relation is a recursive form of an equation, for example: A recurrence relation can be put into an equivalent closed form without the recursion

14 14 Converting Recurrence Relations Begin by looking at a series of equations with decreasing values of n:

15 15 Converting Recurrence Relations Now, we substitute back into the first equation:

16 16 Converting Recurrence Relations We stop when we get to T(1): How many “+ 2” terms are there? Notice we increase them with each substitution.

17 17 Converting Recurrence Relations We must have n – 1 of the “+ 2” terms because there was one at the start and we did n – 2 substitutions: So, the closed form of the equation is:

18 18 Approximating Recurrence Relations For recurrence relations of the form T(N) = a * T(N/b) + f(N) where f(N) = Θ(N d ), the closed form can be approximated by:

19 19 Closest Pair Problem Given a set of N points in space, which two are the closest? A brute force method calculates the distance between every pair of points using: But this does (N 2 – N)/2 distance calculations

20 20 Brute Force Algorithm smallDist = ∞ for i = 1 to N do for j = i+1 to N do dist = sqrt( (xi – xj) 2 + (yi – yj) 2 ) if dist < smallDist then smallDist = dist first = i second = j end if end for end for

21 21 A Divide and Conquer Solution Divide the set of points in into a right and left half Find the closest pair in the right and left half (recursively) Determine (d s ) the shortest of these two distances Check if there is a pair of points within d s units but on opposite sides of the dividing line that are closer

22 22 Divide and Conquer Example

23 23 Divide and Conquer Example

24 24 Divide and Conquer Example

25 25 Divide and Conquer Example

26 26 Divide and Conquer Closest Pair Part 1 ClosestPair( Px, Py, d, p1, p2) // Px the points sorted by x coordinate // Py the points sorted by y coordinate // d the shortest distance between points p1 and p2 // p1 the first point // p2 the second point if sizeOf(Px)  3 then find d, p1, and p2 by brute force return end if construct Lx, Ly, Rx, Ry ClosestPair(Lx, Ly, dl, L1, L2) ClosestPair(Rx, Ry, dr, R1, R2)

27 27 Divide and Conquer Closest Pair 2 d = minimum(dl, dr) if d == dl then p1 = L1 p2 = L2 else p1 = R1 p2 = R2 end if construct Mx and My for i = 1 to sizeOf(My)-1 do for j = i+1 to i+7 (with j  sizeOf(My)) do temp = distance(Myi, Myj) if temp < d then d = temp p1 = Myi p2 = Myj end if end for end for

28 28 Divide and Conquer Closest Point Analysis The combination step looks at the seven points closest to those points within d s of the dividing line The points are divided into two halves Therefore, the recurrence relation is T(N) = 2 * T(N/2) +  (N) This algorithm is  (N lg N)

29 29 Convex Regions A region is convex if a line connecting every pair of points in the region lies entirely within the region

30 30 Convex Hull A convex hull for a set of points is the smallest convex region including all of the points All of the points lie on one side of each edge of the convex hull

31 31 Brute Force Convex Hull Consider the line defined by the first pair of points If all of the other points lie on one side of that line, the line is part of the convex hull Repeat this process for every other pair of points This process is O(N 3 )

32 32 A Divide and Conquer Solution The leftmost and rightmost points are on the convex hull Use the line between these points to divide the set of points into an upper and lower set Find the convex hull of the two parts The convex hull of the entire set is the convex hulls of these two parts without the dividing line

33 33 A Divide and Conquer Solution To find the convex hull of each part –Find the point farthest away from the dividing line –If the points are inside the triangle formed with this point, this is the convex hull –If there are points outside one of these two edges, recursively find the convex hull of those points –If necessary, repeat for the other edge

34 34 Divide and Conquer Example

35 35 Divide and Conquer Example

36 36 Divide and Conquer Example

37 37 Divide and Conquer Convex Hull quickHull(S, ps, pe) if S == {} then return [] // the empty list else pf = point of S farthest from the dividing line PR = set of points to the right of the line between ps and pf PL = set of points to the right of the line between pf and pe return quickHull(PR, ps, pf) + [pf] + quickHull(PL, pf, pe) end if

38 38 Divide and Conquer Convex Hull Analysis If the algorithm divides the points into two halves, the recurrence relation is T(N) = 2 * T(N/2) +  (N) and the closed form is  (N lg N) In the worst case, all the points wind up on one side of each dividing line and the algorithm is then O(N 2 )

39 39 Permutations The permutation of a set of elements is an ordering of those elements The permutations of the numbers from 1 to 3 are [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1] If there are N elements in the set, there are N! permutations

40 40 Recursive Permutations Swap pairs of list values during the recursion Output the list when the “bottom” of the recursion is reached The algorithm by Heap will permute the elements at the front of the list and will then swap in the next element It then permutes the front elements again

41 41 Recursive Permutations Algorithm heapPermute(n) // list is a global variable if n == 0 then output list else for i = 1 to n do heapPermute(n-1) if n is odd then swap list[1] and list[n] else swap list[i] and list[n] end if end for end if

42 42 Iterative Permutations Permutations can be listed in lexical order The position within this list is a permutation’s rank in the range [0, N! – 1] It is possible to iteratively generate the permutation from this rank number by using the factorial of the values from 1 to N

43 43 Iterative Permutations Algorithm list[size] = 1 for j = 1 to size – 1 do d = (rank mod f[j + 1]) / f[j] rank = rank – d * f[j] list[size – j] = d+1 for i = size – j + 1 to size do if list[i] > d then list[i] = list[i] + 1 end if end for end for

44 44 Recursion and Stacks Every subprogram has an Activation Record (AR) that includes the space needed for parameters, local variables, a return value, and a place to return control when done Every time a subprogram is called during execution, an instance of this AR is created and placed on the system stack

45 45 Recursion and Stacks When a subprogram completes, its AR instance (ARI) is removed from the system stack For recursive subprograms, there will be multiple ARIs on the stack – one for each call

46 46 Recursion and Stacks A recursive subprogram could be rewritten to remove recursion by using a programmer created stack to keep track of what would be on the system stack Tracing recursive subprograms is easier if you simulate the system stack by drawing boxes when subprograms are called and crossing them out when the subprogram finishes


Download ppt "Chapter 2 Recursive Algorithms. 2 Chapter Outline Analyzing recursive algorithms Recurrence relations Closest pair algorithms Convex hull algorithms Generating."

Similar presentations


Ads by Google