89
Introduction to Algorithms Rabie A. Ramadan [email protected] http://www. rabieramadan.org 6 Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials

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

Embed Size (px)

DESCRIPTION

Convex Hull 3  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

Citation preview

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

Introduction to Algorithms

Rabie A. [email protected]

http://www. rabieramadan.org

6

Ack : Carola Wenk nad Dr. Thomas Ottmann tutorials

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

The First Problem

2

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

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

Convex Hull

3

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

0

2

1

34

6

5

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

Brute force Solution

4

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 )

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

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

P1

P2

Pmax

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

QuickHull Algorithm

6

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 : O(n2)

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

Convex Hull

7

Could you Solve the Convex Hull Problem in O(nlogn) ?

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

Convex Hull: Divide & Conquer

8

· 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

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

Convex Hull: Runtime

9

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

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

Convex Hull: Runtime

10

· Runtime Recurrence: T(n) = 2 T(n/2) + n

· Solves to T(n) = (n log n)

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

Merging in O(n) time

11

· Find upper and lower tangents in O(n) time· Compute the convex hull of AB:· 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

A B

1

2

34

5

6

7

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

QuickHull

12

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

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

Finding the lower tangent in O(n) time

13

can be checked in constant timeHow?

Check only A+1 and A-1 for instance

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-1 } while T not lower tangent to convex hull of B do{ b=b+1 } }

A B0

a=2

1

5

3

4

0

1

2

3

4=b

5

67

T is lower tangent if all the points are above the line

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

Convex Hull – Divide & Conquer

14

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

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

Convex Hull – Divide & Conquer

15

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

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

16

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

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

17

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

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

18

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

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

19

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

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

20

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

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

21

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

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

22

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

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

23

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

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

24

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

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

25

Merging two convex hulls.

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

26

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

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

27

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

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

28

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

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

29

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

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

30

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

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

31

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

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

32

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

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

33

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

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

34

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

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

35

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

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

36

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

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

37

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

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

38

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

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

39

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

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

40

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

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

41

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

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

42

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

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

Chapter 5

Decrease-and-Conquer

Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

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

Decrease-and-Conquer

1. Reduce problem instance to smaller instance of the same problem

2. Solve smaller instance3. Extend solution of smaller

instance to obtain solution to original instance

Also referred to as inductive or incremental approach

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

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.

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

The Problem

46

Consider the problem of exponentiation: Compute an ?

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

Solutions an= a*a*a*a*...*a

an= an/2 * an/2 (more accurately, an= an/2 * a n/2│)

an= an-1* a

an= (an/2)2

Divide and conquer:

Brute Force

Decrease by constant factor

Decrease by one

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

What is the difference?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

T(n) = T(n/a) + a-1 = (a-1) n = when a = 2

alogn2log

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

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?

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

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.

Used in many applications such as network load balancing

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

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)

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

Decrease by OneDepth-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?

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

Algorithm for DFS

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

Example: DFS traversal of undirected graph

a b

e f

c d

g h

DFS traversal stack:DFS tree:

a b

e f

c d

g h

a ab abf

abfe

abf

ab abg

abgc

abgc

dab

gcdh

abgc

d… Red edges are tree edges and

other edges are back edges.

1 2

54

6

3

7

8

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

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)

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

The Problem

Finding paths from a vertex to all other vertices with the

smallest number of edges

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

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.

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

Example of BFS traversal of undirected graph

BFS traversal queue:

a b

e f

c d

g h

BFS tree:

a b

e f

c d

g h

a bef

efg

fg g ch hd d Red edges are tree edges and white edges are cross edges.

1

3

2 6

4 75

8

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

Write an Algorithm for BFS Using a queue?

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

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

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

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.

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

Topological Sorting Example

Order the following items in a food chain

fish

human

shrimp

sheep

wheatplankton

tiger

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

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.

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

Example

Complexity: as DFS

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

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.

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

Example

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

Source removal algorithm Efficiency

Efficiency: same as efficiency of the DFS-based algorithm

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

Decrease-by-Constant-Factor AlgorithmsIn 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

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

Russian Peasant Multiplication

The problem: Compute the product of two positive integersCan 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 2

n – 1 2

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

Example of Russian Peasant Multiplication

Compute 20 * 26 n m

20 26 10 52 5 104 104 2 208 + 1 416 416 520

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

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 . RepeatDecrease by factor 2 algorithm

Decrease by factor 3 algorithm (Q3 on page 187 of Levitin) (your assignment)

T(n) = log n

T(n) n3log

What about odd n?

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

Variable-Size-Decrease AlgorithmsIn 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

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

Euclid’s AlgorithmEuclid’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)

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

Selection ProblemFind 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 averagevalue of a sample. In fact, it is a better (more robust) indicator than

the mean, which is used for the same purpose.

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

Algorithms for the Selection Problem

The sorting-based algorithm: Sort and return the k-th elementEfficiency (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]

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

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 44, 1, 10, 9, 7, 12, 8, 2, 152, 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, 15Since s =6 and k=5 proceed with the left part , Select 8 as a pivot 8, 77 , 8Now s=k=5 and the 5th smallest item is 8

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

Part of your assignment

Report the complexity of the previous algorithm?

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

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

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

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

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

Chapter 6

Transform-and-Conquer

Copyright © 2007 Pearson Addison-Wesley. All rights reserved.

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

Transform and ConquerThis 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)

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

Instance simplification - PresortingSolve a problem’s instance by transforming it into another simpler/easier

instance of the same problem

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

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

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

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

Searching with presortingProblem: 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?

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

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)

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

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 = b1 a11x1+ a12x2 + … + a1nxn = b1 a21x1 + a22x2 + … + a2nxn = b2 a22x2 + … + a2nxn = b2

an1x1 + an2x2 + … + annxn = bn annxn = bn

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

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

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

Example of Gaussian Elimination

Solve 2x1 - 4x2 + x3 = 6 3x1 - x2 + x3 = 11 x1 + x2 - x3 = -3

Gaussian elimination 2 -4 1 6 2 -4 1 6 3 -1 1 11 row2 – (3/2)*row1 0 5 -1/2 2 1 1 -1 -3 row3 – (1/2)*row1 0 3 -3/2 -6 row3–(3/5)*row2

2 -4 1 6 0 5 -1/2 2 0 0 -6/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

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

Pseudocode and Efficiency of Gaussian Elimination

Stage 1: Reduction to the upper-triangular matrixfor 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 substitutionfor 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?