Design of Algorithms

Divide and Conquer

Divide and Conquer

Table of Contents

Overview

divide_and_conquer

General divide and conquer recurrence relation

\[T(n) = aT(\frac{a}{b}) + f(n)\] \[T(n)\in\begin{cases}\Theta(n^k)\text{ if }a<b^k\\\ \Theta(n^k\log{n})\text{ if }a=b^k\\\ \Theta(n^{\log{a}_b)}\text{ if }a>b^k\end{cases}\]

Binary Tree

binary_tree

Height

"""
Recusively compute height of binary tree
input: binary tree T
output: height of T
"""
Height(T):
    if T is empty:
        return -1
    else:
        return max(Height(T_L), Height(T_R) + 1
\[A(n(T)) = A(n(T_L)) + A(n(T_R)) + 1\]

So

\[x = n+1\]

Number of comparisons to empty tree $C(n)$ is then: \(C(n) = n+x = n + 1\) Number of additions $A(n)$ is: \(A(n) = n\)

Tree traversals

tree_traversals

Closest Pair

\(T(n)=2T(\frac{n}{2})+f(n)\) where $f(n)\in\Theta(n)$ Applying master theorem, with $a=2, b=2, d=1$: \(T(n)\in\Theta(n\log{n})\)

EfficientClosestPair(P, Q):
# solve closest pair using divide and conquer
# input: array P of n >= 2 points sorted in nondecreasing order in x-coord
#        array Q in >= 2 points sorted in nondecreasing order in y-coord
# output: euclidean distance between closest pair of points
if n <= 3:
    return BruteForceClosestPair(P, Q)
else:
    copy first ceil(n/2) points of P to array P_l
    copy same ceil(n/2) points of Q to array Q_l
    copy remaining floor(n/2) points of P to array P_r
    copy same floor(n/2) points of Q to Q_r
    d_l = EfficientClosestPair(P_l, Q_l)
    d_r = EfficientClosestPair(P_r, Q_r)
    d = min(d_l, d_r)
    m = P[ceil(n/2)-1].x
    copy all points of Q for which abs(x-m) < d into S[0..num-1]
    dminsq = d^2
    for i = 0 to num-2:
        k = i + 1
        while k <= num-1 and (S[k].y-S[i].y)^2 < dminsq:
            dminsq = min((S[k].x-S[i].x)^2+(S[k].y-S[i].y)^2, dminsq)
            k += 1
    
    return sqrt(dminsq)

Topological Sorting

digraph_traversal (a) Digraph (b) DFS forest of digraph for DFS traversal started at $a$

DFS topological sort


Edit this page.