1 decrease-and-conquer 1. reduce problem instance to smaller instance of the same problem 2. solve...

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

Upload: tracy-logan

Post on 31-Dec-2015

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

1

Decrease-and-ConquerDecrease-and-Conquer

1.1. Reduce problem instance to smaller instance of Reduce problem instance to smaller instance of the same problemthe same problem

2.2. Solve smaller instanceSolve smaller instance

3.3. Extend solution of smaller instance to obtain Extend solution of smaller instance to obtain solution to original instancesolution to original instance

Can be implemented either top-down or bottom-upCan be implemented either top-down or bottom-up Also referred to as Also referred to as inductiveinductive or or incremental incremental approach approach

Page 2: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

2

3 Types of Decrease and Conquer3 Types of Decrease and Conquer

Decrease by a constant Decrease by a constant (usually by 1):(usually by 1):• insertion sortinsertion sort• topological sortingtopological sorting• algorithms for generating permutations, subsetsalgorithms for generating permutations, subsets

Decrease by a constant factorDecrease by a constant factor (usually by half) (usually by half)• binary search and bisection methodbinary search and bisection method• exponentiation by squaringexponentiation by squaring• multiplication multiplication à la russeà la russe

Variable-size decreaseVariable-size decrease• Euclid’s algorithmEuclid’s algorithm• selection by partitionselection by partition• Nim-like gamesNim-like games

Page 3: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

3

What’s the difference?What’s the difference?

Consider the problem of exponentiation: Compute Consider the problem of exponentiation: Compute aann

Brute Force:Brute Force:

Divide and conquer:Divide and conquer:

Decrease by one:Decrease by one:

Decrease by constant factor:Decrease by constant factor:

Page 4: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

4

Insertion SortInsertion Sort

To sort array A[0..To sort array A[0..nn-1], sort A[0..-1], sort A[0..nn-2] recursively and-2] recursively and

then insert A[then insert A[nn-1] in its proper place among the sorted-1] in its proper place among the sorted

A[0..A[0..nn-2]-2]

Usually implemented bottom up (nonrecursively)Usually implemented bottom up (nonrecursively)

Example: Sort 6, 4, 1, 8, 5Example: Sort 6, 4, 1, 8, 5

6 | 6 | 44 1 8 5 1 8 5 4 6 | 4 6 | 11 8 5 8 5 1 4 6 | 1 4 6 | 88 5 5 1 4 6 8 | 1 4 6 8 | 55 1 4 5 6 81 4 5 6 8

Page 5: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

5

Pseudocode of Insertion Sort Pseudocode of Insertion Sort

Page 6: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

6

Analysis of Insertion SortAnalysis of Insertion Sort

Time efficiencyTime efficiency

CCworstworst((nn) = ) = nn((nn-1)/2 -1)/2 ΘΘ((nn22))

CCavgavg((nn) ) ≈≈ nn22/4 /4 ΘΘ((nn22))

CCbestbest((nn) = ) = nn - 1 - 1 ΘΘ((nn)) (also fast on almost sorted arrays)(also fast on almost sorted arrays)

Space efficiency: in-placeSpace efficiency: in-place

Stability: yesStability: yes

Best elementary sorting algorithm overallBest elementary sorting algorithm overall

Binary insertion sortBinary insertion sort

Page 7: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

7

Dags and Topological SortingDags and Topological Sorting

A A dagdag: a directed acyclic graph, i.e. a directed graph with no : a directed acyclic graph, i.e. a directed graph with no (directed) cycles(directed) cycles

Arise in modeling many problems that involve prerequisiteArise in modeling many problems that involve prerequisiteconstraints (construction projects, document version control)constraints (construction projects, document version control)

Vertices of a dag can be linearly ordered so that for every edgeVertices of a dag can be linearly ordered so that for every edgeits starting vertex is listed before its ending vertex (its starting vertex is listed before its ending vertex (topological topological sorting sorting). Being a dag is also a necessary condition for ). Being a dag is also a necessary condition for topological sorting be possible. topological sorting be possible.

a b

c d

a b

c d

a daga dag not a dagnot a dag

Page 8: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

8

Topological Sorting ExampleTopological Sorting Example

Order the following items in a food chainOrder the following items in a food chain

fish

human

shrimp

sheep

wheatplankton

tiger

Page 9: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

9

DFS-based AlgorithmDFS-based Algorithm

DFS-based algorithm for topological sortingDFS-based algorithm for topological sorting• Perform DFS traversal, noting the order vertices are Perform DFS traversal, noting the order vertices are

popped off the traversal stackpopped off the traversal stack• Reverse order solves topological sorting problemReverse order solves topological sorting problem• Back edges encountered?Back edges encountered?→→ NOT a dag! NOT a dag!

Example:Example:

Efficiency: Efficiency:

a b

e f

c d

g h

Page 10: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

10

Source Removal AlgorithmSource Removal Algorithm

Source removal algorithmSource removal algorithm Repeatedly identify and remove a Repeatedly identify and remove a sourcesource (a vertex with no (a vertex with no incoming edges) and all the edges incident to it until either incoming edges) and all the edges incident to it until either no vertex is left (problem is solved) or there is no source no vertex is left (problem is solved) or there is no source among remaining vertices (not a dag)among remaining vertices (not a dag)

Example:Example:

Efficiency: same as efficiency of the DFS-based algorithmEfficiency: same as efficiency of the DFS-based algorithm

a b

e f

c d

g h

Page 11: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

11

Generating Permutations Generating Permutations

Minimal-changeMinimal-change decrease-by-one algorithm decrease-by-one algorithmIf If n = n = 1 return 1; otherwise, generate recursively the list of all 1 return 1; otherwise, generate recursively the list of all

permutations of 12…permutations of 12…n-n-1 and then insert 1 and then insert n n into each of into each of those permutations by starting with inserting those permutations by starting with inserting nn into 12... into 12...nn-1 -1 by moving right to left and then switching direction for by moving right to left and then switching direction for each new permutationeach new permutation

Example: Example: nn=3=3startstart 1 1 insert 2 into 1 right to leftinsert 2 into 1 right to left 1212 2121insert 3 into 12 right to left 123insert 3 into 12 right to left 123 132132 312312insert 3 into 21 left to rightinsert 3 into 21 left to right 321321 231231 213213

Page 12: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

12

Other permutation generating algorithmsOther permutation generating algorithms

Johnson-Trotter (p. 145)Johnson-Trotter (p. 145)

Lexicographic-order algorithm (p. 146)Lexicographic-order algorithm (p. 146)

Heap’s algorithm (Problem 4 in Exercises 4.3)Heap’s algorithm (Problem 4 in Exercises 4.3)

Page 13: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

13

Generating SubsetsGenerating Subsets

Binary reflected Gray codeBinary reflected Gray code: minimal-change algorithm for : minimal-change algorithm for generating 2generating 2n n bit strings corresponding to all the subsets of bit strings corresponding to all the subsets of an an nn-element set where -element set where nn > 0 > 0

If If nn=1 make list =1 make list L L of two bit strings 0 and 1of two bit strings 0 and 1

elseelse

generate recursively list generate recursively list LL1 of bit strings of length 1 of bit strings of length nn-1-1

copy list copy list LL1 in reverse order to get list 1 in reverse order to get list LL2 2

add 0 in front of each bit string in list add 0 in front of each bit string in list LL11

add 1 in front of each bit string in list add 1 in front of each bit string in list LL22

append append LL2 to 2 to LL1 to get 1 to get LL

return return LL

Page 14: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

14

Decrease-by-Constant-Factor AlgorithmsDecrease-by-Constant-Factor Algorithms

In this variation of decrease-and-conquer, instance size In this variation of decrease-and-conquer, instance size is reduced by the same factor (typically, 2) is reduced by the same factor (typically, 2)

Examples:Examples:• binary search and the method of bisectionbinary search and the method of bisection

• exponentiation by squaringexponentiation by squaring

• multiplication multiplication àà la russe (Russian peasant method) la russe (Russian peasant method)

• fake-coin puzzlefake-coin puzzle

• Josephus problemJosephus problem

Page 15: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

15

Binary SearchBinary Search

Very efficient algorithm for searching in Very efficient algorithm for searching in sorted arraysorted array:: KK

vsvsA[0] . . . A[A[0] . . . A[mm] . . . A[] . . . A[nn-1]-1]

If If K = K = A[A[mm], stop (successful search); otherwise, continue], stop (successful search); otherwise, continuesearching by the same method in A[0..searching by the same method in A[0..mm-1] if -1] if K < K < A[A[mm]]and in A[and in A[mm+1..+1..nn-1] if -1] if K > K > A[A[mm]]

l l 0; 0; rr nn-1-1while while ll rr do do

mm ((ll++rr)/2)/2 if if K = K = A[A[mm] return ] return mm else if else if K < K < A[A[mm] ] r r mm-1-1 else else l l mm+1+1return -1return -1

Page 16: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

16

Analysis of Binary SearchAnalysis of Binary Search Time efficiencyTime efficiency

• worst-case recurrence: worst-case recurrence: CCw w ((nn) = 1 + ) = 1 + CCww( ( nn/2/2 ), ), CCw w (1) = 1 (1) = 1 solution: solution: CCww((nn) =) = loglog22((nn+1)+1)

This is VERY fast: This is VERY fast: e.g., Ce.g., Cww(10(1066) = 20) = 20

Optimal for searching a sorted arrayOptimal for searching a sorted array

Limitations: must be a sorted array (not linked list)Limitations: must be a sorted array (not linked list)

Bad (degenerate) example of divide-and-conquerBad (degenerate) example of divide-and-conquer

Has a continuous counterpart called Has a continuous counterpart called bisection methodbisection method for for solving equations in one unknown solving equations in one unknown ff((xx) ) = = 0 (see Sec. 12.4)0 (see Sec. 12.4)

Page 17: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

17

Exponentiation by SquaringExponentiation by Squaring

The problem: Compute The problem: Compute aann where where n n is a nonnegative integeris a nonnegative integer

The problem can be solved by applying recursively the formulas:The problem can be solved by applying recursively the formulas:

For even values of For even values of nn

For odd values of For odd values of nn

a a nn = ((a a nn/2 /2 ))2 2 if if n n > 0 and > 0 and a a 0 0 = 1= 1

a a nn = ((a a ((n-n-1)/21)/2 ) )2 2 aa

Recurrence: M(Recurrence: M(nn) = M( ) = M( nn/2/2 ) + f ) + f(n(n)),, where f( where f(nn) = 1 or 2, ) = 1 or 2,

M(0) = 0M(0) = 0

Master Theorem: M(Master Theorem: M(nn)) ΘΘ(log (log nn) = ) = ΘΘ((bb) where ) where b = b = loglog22((n+n+1)1)

Page 18: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

18

Russian Peasant MultiplicationRussian Peasant Multiplication

The problem: Compute the product of two positive integersThe problem: Compute the product of two positive integers

Can be solved by a decrease-by-half algorithm based on the Can be solved by a decrease-by-half algorithm based on the following formulas.following formulas.

For even values of For even values of nn::

For odd values of For odd values of nn::

nn * * mm = * 2 = * 2mm

n n * * mm = * 2 = * 2m + m m + m if if nn > 1 and > 1 and m m if if n n = 1 = 1

n n 22

nn – 1 – 1 22

Page 19: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

19

Example of Russian Peasant MultiplicationExample of Russian Peasant Multiplication

Compute 20 Compute 20 * 26* 26

n mn m

20 2620 26

10 5210 52

5 104 1045 104 104

2 208 +2 208 +

1 416 4161 416 416

520520

Note:Note: Method reduces to adding Method reduces to adding mm’s’s values corresponding tovalues corresponding to odd odd nn’s.’s.

Page 20: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

20

Fake-Coin Puzzle (simpler version)Fake-Coin Puzzle (simpler version)

There are There are nn identically looking coins one of which is fake. identically looking coins one of which is fake. There is a balance scale but there are no weights; the scale can 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 tell whether two sets of coins weigh the same and, if not, which of the two sets is heavier (but not by how much). Design an of the two sets is heavier (but not by how much). Design an efficient algorithm for detecting the fake coin. Assume that efficient algorithm for detecting the fake coin. Assume that the fake coin is known to be lighter than the genuine ones.the fake coin is known to be lighter than the genuine ones.

Decrease by factor 2 algorithmDecrease by factor 2 algorithm

Decrease by factor 3 algorithm Decrease by factor 3 algorithm

Page 21: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

21

Variable-Size-Decrease AlgorithmsVariable-Size-Decrease Algorithms

In the variable-size-decrease variation of decrease-and-In the variable-size-decrease variation of decrease-and-conquer, instance size reduction varies from one conquer, instance size reduction varies from one iteration to anotheriteration to another

Examples:Examples:• Euclid’s algorithm for greatest common divisorEuclid’s algorithm for greatest common divisor• partition-based algorithm for selection problempartition-based algorithm for selection problem• interpolation searchinterpolation search• some algorithms on binary search treessome algorithms on binary search trees• Nim and Nim-like gamesNim and Nim-like games

Page 22: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

22

Euclid’s algorithm is based on repeated application of equalityEuclid’s algorithm is based on repeated application of equalitygcd(gcd(m, nm, n) = gcd() = gcd(n, m n, m mod mod nn))

Ex.: Ex.: gcd(80,44) = gcd(44,36) = gcd(36, 12) = gcd(12,0) = 12gcd(80,44) = gcd(44,36) = gcd(36, 12) = gcd(12,0) = 12

One can prove that the size, measured by the second number,One can prove that the size, measured by the second number,decreases at least by half after two consecutive iterations. decreases at least by half after two consecutive iterations. Hence, T(Hence, T(nn) ) O(log O(log nn))

Euclid’s AlgorithmEuclid’s Algorithm

Page 23: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

23

Selection ProblemSelection Problem

Find the Find the kk-th smallest element in a list of -th smallest element in a list of nn numbers numbers k = k = 1 or 1 or k k = = nn

medianmedian: : kk = = n/2n/2

Example: Example: 4, 1, 10, 9, 7, 12, 8, 2, 154, 1, 10, 9, 7, 12, 8, 2, 15 median median = ?= ?

The median is used in statistics as a measure of an averageThe median is used in statistics as a measure of an averagevalue of a sample. In fact, it is a better (more robust) indicatorvalue of a sample. In fact, it is a better (more robust) indicatorthan the mean, which is used for the same purpose.than the mean, which is used for the same purpose.

Page 24: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

24

Digression: Post Office Location ProblemDigression: Post Office Location Problem

Given Given n n village locations along a straight highway, where village locations along a straight highway, where should a new post office be located to minimize the average should a new post office be located to minimize the average distance from the villages to the post office?distance from the villages to the post office?

Page 25: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

25

Algorithms for the Selection ProblemAlgorithms for the Selection Problem

The sorting-based algorithm: Sort and return the The sorting-based algorithm: Sort and return the kk-th element-th elementEfficiency (if sorted by mergesort): Efficiency (if sorted by mergesort): ΘΘ((nnlog log nn))

A faster algorithm is based on the array A faster algorithm is based on the array partitioningpartitioning: :

Assuming that the array is indexed from 0 to Assuming that the array is indexed from 0 to nn-1-1 and and s s is a split is a split position obtained by the array partitioning:position obtained by the array partitioning:If If s = ks = k-1, the problem is solved;-1, the problem is solved;if if s > ks > k-1, look for the -1, look for the k-k-th smallest element in the left part;th smallest element in the left part;if if s < ks < k-1, look for the (-1, look for the (kk--ss)-th smallest element in the right part.)-th smallest element in the right part.

Note: The algorithm can simply continue untilNote: The algorithm can simply continue until s = s = kk-1.-1.

sall are ≤ A[s] all are ≥ A[s]

Page 26: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

26

Two Partitioning AlgorithmsTwo Partitioning Algorithms

There are two principal ways to partition an array:There are two principal ways to partition an array:

One-directional scan (Lomuto’s partitioning algorithm)One-directional scan (Lomuto’s partitioning algorithm)

Two-directional scan (Hoare’s partitioning algorithm)Two-directional scan (Hoare’s partitioning algorithm)

Page 27: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

27

Lomuto’s Partitioning AlgorithmLomuto’s Partitioning Algorithm

Scans the array left to right maintaining the array’s partition Scans the array left to right maintaining the array’s partition into three contiguous sections: < into three contiguous sections: < pp, , pp, and unknown, where , and unknown, where pp is the value of the first element (the partition’s is the value of the first element (the partition’s pivotpivot). ).

On each iteration the unknown section is decreased by one On each iteration the unknown section is decreased by one element until it’s empty and a partition is achieved by element until it’s empty and a partition is achieved by exchanging the pivot with the element in the split position exchanging the pivot with the element in the split position s.s.

p < p >= p ?

l s i r

p < p >= p

l s r

Page 28: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

28

Tracing Lomuto’s Partioning AlgorithmTracing Lomuto’s Partioning Algorithm

ss ii

44 11 1010 88 77 1212 99 22 1515

ss ii

44 11 1010 88 77 1212 99 22 1515

ss ii

44 11 1010 88 77 1212 99 22 1515

ss ii

44 11 22 88 77 1212 99 1010 1515

ss

44 11 22 88 77 1212 99 1010 1515

22 11 44 88 77 1212 99 1010 1515

Page 29: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

29

Tracing Quickselect (Partition-based Algorithm)Tracing Quickselect (Partition-based Algorithm)

Find the median of 4, 1, 10, 9, 7, 12, 8, 2, 15Find the median of 4, 1, 10, 9, 7, 12, 8, 2, 15

Here: Here: nn = 9, = 9, kk = = 9/29/2 = 5, = 5, kk -1=4 -1=4

00 11 22 33 44 55 66 77 88

44 11 1010 88 77 1212 99 22 1515

22 11 44 88 77 1212 99 1010 1515

88 77 1212 99 1010 1515

77 88 1212 99 1010 1515

after 1st partitioning: s=2<k-1=4

after 2nd partitioning: s=4=k-1

The median is A[4]= 8

Page 30: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

30

Efficiency of QuickselectEfficiency of Quickselect

Average case (average split in the middle): Average case (average split in the middle):

C(C(nn) = C() = C(nn/2)+(/2)+(nn+1) C(+1) C(nn) ) ΘΘ((nn))

Worst case (degenerate split): C(Worst case (degenerate split): C(nn) ) ΘΘ((nn22))

A more sophisticated choice of the pivot leads to a complicated A more sophisticated choice of the pivot leads to a complicated algorithm with algorithm with ΘΘ((nn) worst-case efficiency.) worst-case efficiency.

Page 31: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

31

index

value

A[r]

v

A[l]

l x r

.

.

Interpolation SearchInterpolation Search

Searches a sorted array similar to binary search but estimates Searches a sorted array similar to binary search but estimates location of the search key in location of the search key in AA[[l..rl..r] by using its value ] by using its value v.v. Specifically, the values of the array’s elements are assumed to Specifically, the values of the array’s elements are assumed to grow linearly from grow linearly from AA[[ll] to ] to AA[[rr] and the location of ] and the location of v v is is estimated as the estimated as the xx-coordinate of the point on the straight line -coordinate of the point on the straight line through (through (l, l, A[A[ll]) and (]) and (r, r, A[A[rr]) whose ]) whose yy-coordinate is -coordinate is vv::

xx = = ll + + ((v v - A[- A[ll])(])(rr - - ll)/(A[)/(A[rr] – A[] – A[ll] )] )

Page 32: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

32

Analysis of Interpolation SearchAnalysis of Interpolation Search

EfficiencyEfficiency

average case: C(average case: C(nn)) < log < log22 log log22 nn + 1 + 1

worst case: C(worst case: C(nn) = ) = nn

Preferable to binary search only for VERY large arrays Preferable to binary search only for VERY large arrays and/or expensive comparisonsand/or expensive comparisons

Has a counterpart, the Has a counterpart, the method of false positionmethod of false position ( (regula falsiregula falsi), ), for solving equations in one unknown (Sec. 12.4)for solving equations in one unknown (Sec. 12.4)

Page 33: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

33

Binary Search Tree AlgorithmsBinary Search Tree Algorithms

Several algorithms on BST requires recursive processing of Several algorithms on BST requires recursive processing of just one of its subtrees, e.g.,just one of its subtrees, e.g.,

SearchingSearching

Insertion of a new keyInsertion of a new key

Finding the smallest (or the largest) keyFinding the smallest (or the largest) key

k

<k >k

Page 34: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

34

Searching in Binary Search TreeSearching in Binary Search Tree

Algorithm Algorithm BTSBTS((xx, , vv))//Searches for node with key equal to //Searches for node with key equal to v v in BST rooted at node in BST rooted at node xx if if xx = NIL return = NIL return -1-1 else ifelse if vv = = KK((xx)) return return xx else if else if v < Kv < K((xx)) return return BTSBTS((leftleft((xx)), v, v)) else return else return BTSBTS((rightright((xx)), v, v))

EfficiencyEfficiency

worst case: worst case: C(C(nn) = ) = nn

average case: average case: C(C(nn) ≈ 2ln ) ≈ 2ln n n ≈ 1.39≈ 1.39loglog22 nn

Page 35: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

35

One-Pile NimOne-Pile Nim

There is a pile of There is a pile of n n chips. Two players take turn by removing chips. Two players take turn by removing from the pile at least 1 and at most from the pile at least 1 and at most m m chips. (The number of chips. (The number of chips taken can vary from move to move.) The winner is the chips taken can vary from move to move.) The winner is the player that takes the last chip. Who wins the game – the player player that takes the last chip. Who wins the game – the player moving first or second, if both player make the best moves moving first or second, if both player make the best moves possible?possible?

It’s a good idea to analyze this and similar games “backwards”, It’s a good idea to analyze this and similar games “backwards”, i.e., starting with i.e., starting with n = n = 0, 1, 2, … 0, 1, 2, …

Page 36: 1 Decrease-and-Conquer 1. Reduce problem instance to smaller instance of the same problem 2. Solve smaller instance 3. Extend solution of smaller instance

36

Partial Graph of One-Pile Nim with Partial Graph of One-Pile Nim with m m = 4 = 4

0 5

1

2

3

4

10

6

7

8

9

Vertex numbers indicate Vertex numbers indicate nn, the number of chips in the pile. The , the number of chips in the pile. The losing position for the player to move are circled. Only winning losing position for the player to move are circled. Only winning moves from a winning position are shown (in bold).moves from a winning position are shown (in bold).

GeneralizationGeneralization: The player moving first wins iff : The player moving first wins iff n n is not a is not a multiple of 5 (more generally, multiple of 5 (more generally, mm+1); the+1); the winning move is to take winning move is to take n n mod 5 (mod 5 (n n mod (mod (mm+1))+1)) chips on every move. chips on every move.