Max Heap & Tree Structures Guide
Max Heap & Tree Structures Guide
2 3
4 5 6 7
8 9 7
10 11
8
2 3
4 5 6 7
8 9 7
10 11
8
2 3
4 11 6 7
8 9 7
10 85
2 3
4 11 6 7
8 9 7
10 85
Heapify!
Initializing A Max Heap
1
2 3
9 11 6 7
8 4 7
10 85
Initializing A Max Heap
1
2 3
9 11 6 7
8 4 7
10 85
2 7
9 11 6 3
8 4 7
10 85
Initializing A Max Heap
1
2 7
9 11 6 3
8 4 7
10 85
11 7
9 6 3
8 4 7
10 85
11 7
9 10 6 3
8 4 8 75
11 7
9 10 6 3
8 4 72 8
5
11 7
9 10 6 3
8 4 72 8
5
9 10 6 3
8 4 72 8
5
10 7
9 6 3
8 4 72 8
5
10 7
9 5 6 3
8 4 72 8
10 7
9 5 6 3
8 4 72 8
1
Done.
Initializing a Max Heap*
Time Complexity
11
9 7
8 5 6 3
1 4 7
10 8
2
Height of heap = h.
Number of subtrees with root at level j is <= 2 j-1.
Time for each subtree is O(h-j+1).
Complexity
Time for level j subtrees is <= 2j-1(h-j+1) = t(j).
Total time is t(1) + t(2) + … + t(h-1) = O(n).
Leftist Trees
Linked binary tree.
Can do everything a heap can do and in the
same asymptotic complexity.
Can meld two leftist tree priority queues in
O(log n) time.
Extended Binary Trees
2 1
2 1 1 0
1 1 0 0 1 0
0 0 0 0 0 0
Properties Of s()
Otherwise,
s(x) = min {s(leftChild(x)),
s(rightChild(x))} + 1
Height Biased Leftist Trees
Tree Terminology
A Leftist Tree
2
2 1
2 1 1 0
1 1 0 0 1 0
0 0 0 0 0 0
Leftist Trees--Property 1
2 1
2 1 1 0
1 1 0 0 1 0
0 0 0 0 0 0
2 1
2 1 1 0
1 1 0 0 1 0
0 0 0 0 0 0
4 3
6 8 5
8 6 9
Some Min Leftist Tree Operations
empty()
size()
top()
push()
pop()
meld()
initialize()
push() and pop() use meld().
Push Operation
push(7) 2
4 3
6 8 5
8 6 9
Push Operation
push(7) 2
4 3
6 8 5
8 6 9
4 3
6 8 5
8 6 9
4 3
6 8 5
8 6 9
Remove Min (pop)
2
4 3
6 8 5
8 6 9
4 3
6 8 5
8 6 9
4 3
6 8 5 6
8 6 9
6 8 5 6
8 6 9
6 8 5 6
8 6 9
6 8
8 6
8
Meld Two Min Leftist Trees
4
4
6
6 6
6
8
8 6 8
8 6
5 4
9 6 6
8 6 8
4
5
6 6
9
8 6 8
Initializing In O(n) Time
• create n single node min leftist trees
and place them in a FIFO queue
• repeatedly remove two min leftist trees
from the FIFO queue, meld them, and
put the resulting min leftist tree into the
FIFO queue
• the process terminates when only 1 min
leftist tree remains in the FIFO queue
• analysis is the same as for heap
initialization
Tournament Trees
Winner trees.
Loser Trees.
Winner Trees
Complete binary tree with n external
nodes and n - 1 internal nodes.
External nodes represent tournament
players.
Each internal node represents a match
played between its two children;
the winner of the match is stored at
the internal node.
Root has overall winner.
Winner Tree For 16 Players
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorting.
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sort 16 Numbers
1
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sort 16 Numbers
1
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorted array.
Sort 16 Numbers
1
1
2
3 1 2 2
3 6 5 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorted array.
Sort 16 Numbers
1
1
2
3 3 2 2
3 6 5 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorted array.
Sort 16 Numbers
1
3
2
3 3 2 2
3 6 5 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorted array.
Sort 16 Numbers
2
3
2
3 3 2 2
3 6 5 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Sorted array.
Sort 16 Numbers
2
3
2
3 3 2 2
3 6 5 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 2 2
3 6 5 3 6 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 2
3 6 5 3 6 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 2
3 6 5 3 6 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 2
3 6 5 3 6 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 2
3 6 5 3 6 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 2
3 6 5 3 6 4 5 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2
Sorted array.
Sort 16 Numbers
2
3
2
3 3 4 5
3 6 5 3 6 4 5 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2
Sorted array.
Sort 16 Numbers
2
3
4
3 3 4 5
3 6 5 3 6 4 5 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2
Sorted array.
Sort 16 Numbers
3
3
4
3 3 4 5
3 6 5 3 6 4 5 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2
Sorted array.
Sort 16 Numbers
3
3
4
3 3 4 5
3 6 5 3 6 4 5 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 2 2 3
Sorted array.
Time To Sort
• Initialize
O(n) time
• Get winner
O(1) time
• Remove/replace winner and replay
O(log n) time
more precisely Theta(log n)
Replace Winner And Replay
1
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 6 5 7 3 2 6 9 4 5 2 5 8
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 6 5 7 3 2 6 9 4 5 2 5 8
1
2
3 1 2 2
3 6 1 3 2 4 2 5
4 3 6 8 6 5 7 3 2 6 9 4 5 2 5 8
4 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
6 1
4 8 5 7
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
1
6 3 2
4 8 5 7 6 9
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
1
3
2
6 3 4 2
4 8 5 7 6 9 5 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
1
3
2
6 3 4 5
4 8 5 7 6 9 5 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
1
3
2
6 3 4 5
4 8 5 7 6 9 5 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Min Loser Tree For 16 Players
2
3
2
6 3 4 5
4 8 5 7 6 9 5 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
1 Winner
3
2
6 3 4 5
4 8 5 7 6 9 5 8
4 3 6 8 1 5 7 3 2 6 9 4 5 2 5 8
Complexity Of Loser Tree
Initialize
32
3
2
6 53 4 5
4 8 95 7 6 9 5 8
4 3 6 8 91 5 7 3 2 6 9 4 5 2 5 8
n = 5 packages
weights [2, 5, 6, 3, 4]
truck capacity c = 10
n = 5 packages
weights [2, 5, 6, 3, 4]
truck capacity c = 10
truck1 = [2, 5]
truck2 = [6, 3]
truck3 = [4]
uses 3 trucks when 2 trucks suffice
Truck Loading
n = 5 packages
weights [2, 5, 6, 3, 4]
truck capacity c = 10
truck1 = [2, 5, 3]
truck2 = [6, 4]
Bin Packing
• First Fit.
Bins are arranged in left to right order.
Items are packed one at a time in given order.
Current item is packed into leftmost bin into
which it fits.
If there is no bin into which current item fits,
start a new bin.
First Fit
n=4
weights = [4, 7, 3, 6]
capacity = 10
n=4
weights = [4, 7, 3, 6]
capacity = 10
n=4
weights = [4, 7, 3, 6]
capacity = 10
First Fit
n=4
weights = [4, 7, 3, 6]
capacity = 10
n=4
weights = [4, 7, 3, 6]
capacity = 10
n=4
weights = [4, 7, 3, 6]
capacity = 10
Not optimal.
2 bins suffice.
Bin Packing Heuristics
• Best Fit.
Items are packed one at a time in given order.
To determine the bin for an item, first
determine set S of bins into which the item fits.
If S is empty, then start a new bin and put item
into this new bin.
Otherwise, pack into bin of S that has least
available capacity.
Bin Packing Heuristics
• Dictionary Operations:
find(key)
insert(key, value)
erase(key)
• Additional operations:
ascend()
get(index) (indexed binary search tree)
delete(index) (indexed binary search tree)
Complexity Of Dictionary Operations
find(), insert() and erase()
D is number of buckets
Definition Of Binary Search Tree
• A binary tree.
• Each node has a (key, value) pair.
• For every node x, all keys in the left
subtree of x are smaller than that in x.
• For every node x, all keys in the right
subtree of x are greater than that in x.
Example Binary Search Tree
20
10 40
6 15 30
2 8 25
10 40
6 15 30
2 8 25
10 40
6 15 30
2 8 25
10 40
6 15 30
2 8 25 35
10 40
6 15 30
2 8 25 35
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
Three cases:
Element is in a leaf.
Element is in a degree 1 node.
Element is in a degree 2 node.
Erase From A Leaf
20
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
8 40
6 15 30
18 25 35
2 8
8 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
18 25 35
2 8
10 40
6 15 30
2 8 25 35
Complexity is O(height).
Indexed Binary Search Tree
4 3
10 40
1 0 1
6 15 30
0 0 0 0
1 18
2 8 25 35
0
7
4 3
10 40
1 0 1
6 15 30
0 0 0 0
1 18
2 8 25 35
0
7
4 3
10 40
1 0 1
6 15 30
0 0 0 0
1 18
2 8 25 35
0
7
4 3
e l
1 0 1
b f j
0 0 0 0
1 g
a d i k
0
c
list = [a,b,c,d,e,f,g,h,i,j,k,l]
insert(5,’m’)
7
h
4 3
e l
1 0 1
b f j
0 0 0 0
1 g
a d i k
0
c
list = [a,b,c,d,e,f,g,h,i,j,k,l]
insert(5,’m’)
7
h
4 3
e l
1 0 1
b f j
0 0 0 0
1 g
a d i k
0
c
4 3
e l
1 0 1
b f j
0 0 0 0
1 g
a d i k
0
c
4 3
e l
1 m 0 1
b f j
0 0 0 0
1 g
a d i k
0
c
4 3
e l
1 0 1
b f j
0 0 0 0
1 g
a d m i k
0
c
1 1
0 1 -1
0
0
0 0 -1 0
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -1 0 60
35
1 5 20
0
25
insert(9)
-1
10
0 1 1
7 40
0 1 -1
0 -1 45
3 8 30
0
0 0 0 -1 0 60
35
1 5 9 20
0
25
insert(29)
-1
10
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 -2 -1 35
0 60
1 5 20
0 -1
RR imbalance => new node is in 25
right subtree of right subtree of 0
1 1
7 40
0 1 -1
0 45
3 8 30
0
0 0 0 0 60
35
1 5 25
0 0
20 29
RR rotation.
AVL Rotations
• RR
• LL
• RL
• LR
Red Black Trees
7 40
45
3 8 30
35 60
1 5 20
25
Red Black Trees
7 40
45
3 8 30
35 60
1 5 20
25
Red Black Tree
• G = (V,E)
• V is the vertex set.
• Vertices are also called nodes and points.
• E is the edge set.
• Each edge connects two different vertices.
• Edges are also called arcs and lines.
• Directed edge has an orientation (u,v).
u v
Graphs
2
3
8
1 10
4
5
9
11
6
7
Directed Graph (Digraph)
2
3
8
1 10
4
5
9
11
6
7
Applications—Communication Network
2
3
8
1 10
4
5
9
11
6
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
11
5 6
6 7
7
2
3
8
1 10
4
5
9
11
6
7
2
3
8
1 10
4
5
9
11
6
7
8
10
9
11
2
3
8
1 10
4
5
9
11
6
7
2
3
8
1 10
4
5
9
11
6
7
• Path problems.
• Connectedness problems.
• Spanning tree problems.
• Graph coloring problems.
• Flow network problems.
Path Finding
Path between 1 and 8.
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
11
5 6
6 7
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
11
5 6
6 7
7
2
3
8
1 10
4
5
9
11
6
7
• Undirected graph.
• There is a path between every pair of
vertices.
Example Of Not Connected
2
3
8
1 10
4
5
9
11
6
7
Connected Graph Example
2
3
8
1 10
4
5
9
11
6
7
Connected Components
2
3
8
1 10
4
5
9
11
6
7
Connected Component
2
3
8
1 10
4
5
9
11
6
7
Connected Components
2
3
8
1 10
4
5
9
11
6
7
2
3
8
1 10
4
5
9
11
6
7
2
3
8
1 10
4
5
9
11
6
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
8 11
5 6
2
6 7
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
8 11
5 6
2
6 7
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
8 11
5 6
2
6 7
7
2
4 3
8 8
1 6 10
2 4 5
4 4 3
5
9
8 11
5 6
2
6 7
7
• Adjacency Matrix
• Adjacency Lists
Linked Adjacency Lists
Array Adjacency Lists
Adjacency Matrix
• 0/1 n x n matrix, where n = # of vertices
• A(i,j) = 1 iff (i,j) is an edge
1 2 3 4 5
2
3 1 0 1 0 1 0
2 1 0 0 0 1
1
3 0 0 0 0 1
4 4 1 0 0 0 1
5
5 0 1 1 1 0
Adjacency Matrix Properties
1 2 3 4 5
2
3 1 0 1 0 1 0
2 1 0 0 0 1
1
3 0 0 0 0 1
4 4 1 0 0 0 1
5
5 0 1 1 1 0
•Diagonal entries are zero.
•Adjacency matrix of an undirected graph is
symmetric.
A(i,j) = A(j,i) for all i and j.
Adjacency Matrix (Digraph)
1 2 3 4 5
2
3 1 0 0 0 1 0
2 1 0 0 0 1
1
3 0 0 0 0 0
4 4 0 0 0 0 1
5
5 0 1 1 0 0
•Diagonal entries are zero.
•Adjacency matrix of a digraph need not be
symmetric.
Adjacency Matrix
• n2 bits of space
• For an undirected graph, may store only
lower or upper triangle (exclude diagonal).
(n-1)n/2 bits
• O(n) time to find vertex degree and/or
vertices adjacent to a given vertex.
Adjacency Lists
• Adjacency list for vertex i is a linear list of
vertices adjacent from vertex i.
• An array of n adjacency lists.
aList[1] = (2,4)
2 aList[2] = (1,5)
3
aList[3] = (5)
1
aList[4] = (5,1)
4
5
aList[5] = (2,4,3)
Linked Adjacency Lists
• Each adjacency list is a chain.
2 aList[1] 2 4
3
[2] 1 5
1 [3] 5
[4] 5 1
4
5 aList[5] 2 4 3
Array Length = n
# of chain nodes = 2e (undirected graph)
# of chain nodes = e (digraph)
Array Adjacency Lists
• Each adjacency list is an array list.
2 aList[1] 2 4
3
[2] 1 5
1 [3] 5
[4] 5 1
4
5 aList[5] 2 4 3
Array Length = n
# of list elements = 2e (undirected graph)
# of list elements = e (digraph)
Weighted Graphs
// ADT methods
virtual ~graph() {}
virtual int numberOfVertices() const = 0;
virtual int numberOfEdges() const = 0;
virtual bool existsEdge(int, int) const = 0;
virtual void insertEdge(edge<T>*) = 0;
virtual void eraseEdge(int, int) = 0;
virtual int degree(int) const = 0;
virtual int inDegree(int) const = 0;
virtual int outDegree(int) const = 0;
Abstract Methods Of Graph
2
3
8
1
4
5
9
10
6
7 11
Graph Search Methods
• A search method starts at a given vertex v and
visits/labels/marks every vertex that is reachable
from v.
2
3
8
1
4
5
9
10
6
7 11
Graph Search Methods
• Many graph problems solved using a search
method.
Path from one vertex to another.
Is the graph connected?
Find a spanning tree.
Etc.
• Commonly used search methods:
Breadth-first search. (BFS)
Depth-first search. (DFS)
Breadth-First Search
2
3
8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1 1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 2 4
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 2 4
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 4 5 3 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 4 5 3 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 5 3 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 5 3 6
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 3 6 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 3 6 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 6 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 6 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 9 7
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 7 8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 7 8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8 8
1
4
5
9
10
6
7 11
2
3
FIFO Queue
8
1
4
5
9
10
6
7 11
In other words:
O( |V| + |E| )
Path From Vertex v To Vertex u
2
3
8
1
4
5
9
10
6
7 11
Time Complexity
O(n2) when adjacency matrix used
O(n+e) when adjacency lists used (e
is number of edges)
Spanning Tree
2
3
8
1
4
5
9
6
7
depthFirstSearch(v)
{
Label vertex v as reached.
for (each unreached vertex u
adjacenct from v)
depthFirstSearch(u);
}
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
4
5
9
10
6
7 11
Return to 5.
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
Do a dfs(3).
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
4
5
9
10
6
7 11
Return to 1.
Depth-First Search Example
2
3
8
1
4
5
9
10
6
7 11
• Greedy method.
• Divide and conquer.
• Dynamic Programming.
• Backtracking.
• Branch and bound.
Some Methods Not Covered
• Linear Programming.
• Integer Programming.
• Simulated Annealing.
• Neural Networks.
• Genetic Algorithms.
• Tabu Search.
Optimization Problem
14
A path from 1 to 7.
Path length is 14.
Example
8 6
1
2 3
3 1
16
6 7 4 5 10
4
2 4 7
5 3
14
14
1 3 6 7 11
Greedy Single Source All Destinations
1 3 5 4
Greedy Single Source All Destinations
8 6
1
2 3
3 1
16
6 7 4 5 10
4
2 4 7
5 3
14
1 3 6 [1] [2] [3] [4] [5] [6] [7]
d 0 6 2 9 5- 10 - 14
12
11
p - 1 1 5 3- 3- 416
Greedy Single Source All Destinations
Path Length
1 0
1 3 2
1 3 5 5
1 2 6
[1] [2] [3] [4] [5] [6] [7]
1 3 5 4 9
0 6 2 9 5- 10 - 14
12
11
- 1 1 5 3- 3- 416
1 3 6 10
1 3 6 7 11
Single Source Single Destination
8 10 14
1 3 5 7
7 4 12 6 3
2
2 4 6 8
9
Edge set E.
Operations are:
Is E empty?
Select and remove a least-cost edge.
Use a min heap of edges.
Initialize. O(e) time.
Remove and return least-cost edge. O(log e) time.
Data Structures For Kruskal’s Method
2 4 6 8
• Small instance.
Sort a list that has n <= 10 elements.
Find the minimum of n <= 2 elements.
• Large instance.
Sort a list that has n > 10 elements.
Find the minimum of n > 2 elements.
Solving A Small Instance
• A small instance is solved using some
direct/simple strategy.
Sort a list that has n <= 10 elements.
• Use count, insertion, bubble, or selection sort.
Find the minimum of n <= 2 elements.
• When n = 0, there is no minimum element.
• When n = 1, the single element is the minimum.
• When n = 2, compare the two elements and
determine which is smaller.
Solving A Large Instance
• A large instance is solved as follows:
Divide the large instance into k >= 2 smaller instances.
Solve the smaller instances somehow.
Combine the results of the smaller instances to obtain
the result for the original large instance.
Sort A Large List
• Let n = 2k.
• Let t(k) be the time taken to tile a 2k x 2k
defective chessboard.
• t(0) = d, where d is a constant.
• t(k) = 4t(k-1) + c, when k > 0. Here c is a
constant.
• Recurrence equation for t().
Substitution Method
t(k) = 4t(k-1) + c
= 4[4t(k-2) + c] + c
= 42 t(k-2) + 4c + c
= 42[4t(k-3) + c] + 4c + c
= 43 t(k-3) + 42c + 4c + c
=…
= 4k t(0) + 4k-1c + 4k-2c + ... + 42c + 4c + c
= 4k d + 4k-1c + 4k-2c + ... + 42c + 4c + c
= Theta(4k)
= Theta(number of triominoes placed)
Min And Max
Find the lightest and heaviest of n elements
using a balance that allows you to compare
the weight of 2 elements.
maxElement = 0;
for (int i = 1; i < n; i++)
if (w[maxElement] < w[i]) maxElement = i;
• Small instance.
n <= 2.
Find the min and max element making at most
one comparison.
Large Instance Min And Max
n > 2.
Divide the n elements into 2 groups A and B
with floor(n/2) and ceil(n/2) elements,
respectively.
Find the min and max of each group
recursively.
Overall min is min{min(A), min(B)}.
Overall max is max{max(A), max(B)}.
Min And Max Example
• Find the min and max of {3,5,6,2,4,9,3,1}.
• Large instance.
• A = {3,5,6,2} and B = {4,9,3,1}.
• min(A) = 2, min(B) = 1.
• max(A) = 6, max(B) = 9.
• min{min(A),min(B)} = 1.
• max{max(A), max(B)} = 9.
Dividing Into Smaller Instances
{8,2,6,3,9,1,7,5,4,2,8}
{8,2,6,3,9} {1,7,5,4,2,8}
{2,9} {1,8}
• {2,8,3,6,9,1,7,5,4,2,8 }
• {2,8}, {3,6}, {9,1}, {7,5}, {4,2}, {8}
• mins = {2,3,1,5,2,8}
• maxs = {8,6,9,7,4,8}
• minOfMins = 1
• maxOfMaxs = 9
Comparison Count
• Start with n/2 groups with 2 elements each
and possibly 1 group that has just 1element.
No compares.
• Find the min and max in each group.
floor(n/2) compares.
• Find the min of the mins.
ceil(n/2) - 1 compares.
• Find the max of the maxs.
ceil(n/2) - 1 compares.
• Total is ceil(3n/2) - 2 compares.
Initialize A Heap
• n > 1:
Initialize left subtree and right subtree recursively.
Then do a trickle down operation at the root.
• t(n) = c, n <= 1.
• t(n) = 2t(n/2) + d * height, n > 1.
• c and d are constants.
• Solve to get t(n) = O(n).
• Implemented iteratively in Chapter 12.
Initialize A Loser Tree
• n > 1:
Initialize left subtree.
Initialize right subtree.
Compare winners from left and right subtrees.
Loser is saved in root and winner is returned.
• t(n) = c, n <= 1.
• t(n) = 2t(n/2) + d, n > 1.
• c and d are constants.
• Solve to get t(n) = O(n).
• Implemented iteratively in Chapter 13.
Divide-And-Conquer Sorting
• Small instance.
n <= 1 elements.
n <= 10 elements.
We’ll use n <= 1 for now.
• Large instance.
Divide into k >= 2 smaller instances.
k = 2, 3, 4, … ?
What does each smaller instance look like?
Sort smaller instances recursively.
How do you combine the sorted smaller instances?
Insertion Sort
a[0] a[n-2] a[n-1]
• k=2
• First n - 1 elements (a[0:n-2]) define one of the
smaller instances; last element (a[n-1]) defines
the second smaller instance.
• a[0:n-2] is sorted recursively.
• a[n-1] is a small instance.
Insertion Sort
a[0] a[n-2] a[n-1]
[8, 3] [13, 6] [2, 14] [5] [9, 10] [1] [7, 12] [4]
[8] [3] [13] [6] [2] [14] [9] [10] [7] [12]
Merge Sort
[3, 8] [6, 13] [2, 14] [5] [9, 10] [1] [7, 12] [4]
[8] [3] [13] [6] [2] [14] [9] [10] [7] [12]
Time Complexity
• Let t(n) be the time required to sort n elements.
• t(0) = t(1) = c, where c is a constant.
• When n > 1,
t(n) = t(ceil(n/2)) + t(floor(n/2)) + dn,
where d is a constant.
• To solve the recurrence, assume n is a power of 2
and use repeated substitution.
• t(n) = O(n log n).
Nonrecursive Version
[8] [3] [13] [6] [2] [14] [5] [9] [10] [1] [7] [12] [4]
[3, 8] [6, 13] [2, 14] [5, 9] [1, 10] [7, 12] [4]
6 2 8 5 11 10 4 1 9 7 3
2 5 4 1 3 6 7 9 10 11 8
pivot
Partitioning Example Using
Additional Array
a 6 2 8 5 11 10 4 1 9 7 3
b 2 5 4 1 3 6 7 9 10 11 8
a 6 2 3 5 11 10 4 1 9 7 8
a 6 2 3 5 1 10 4 11 9 7 8
a 6 2 3 5 1 4 10
10 11 9 7 8
• Quick sort.
Switch to heap sort when number of subdiviions
exceed some constant times log2n.
Switch to insertion sort when segment size becomes
small.
C++ STL stable_sort Function
A B
• Divide so that points in A have x-coordinate
<= that of points in B.
Example
d1
A B
• Find closest pair in A.
• Let d1 be the distance between the points in
this pair.
Example
d1
d2
A B
• Find closest pair in B.
• Let d2 be the distance between the points in
this pair.
Example
d1
d2
A B
• Let d = min{d1, d2}.
• Is there a pair with one point in A, the other in
B and distance < d?
Example
A RA RB B
• Candidates lie within d of the dividing line.
• Call these regions RA and RB, respectively.
Example
A RA RB B
• Let q be a point in RA.
• q need be paired only with those points in RB that are
within d of q.y.
Example
q 2d
d
A RA RB B
• Points that are to be paired with q are in a d x 2d
rectangle of RB (comparing region of q).
• Points in this rectangle are at least d apart.
Example
q 2d
d
A RA RB B
• So the comparing region of q has at most 6 points.
• So number of pairs to check is <= 6| RA | = O(n).
Time Complexity
• Sequence of decisions.
• Problem state.
• Principle of optimality.
• Dynamic Programming Recurrence
Equations.
• Solution of recurrence equations.
Sequence Of Decisions
f(1,c)
f(2,c) f(2,c-w1)
f(5,c)
f(5,c-w1 –w3 –w4)
Time Complexity
• Let t(n) be the time required when n items are
available.
• t(0) = t(1) = a, where a is a constant.
• When t > 1,
t(n) <= 2t(n-1) + b,
where b is a constant.
• t(n) = O(2n).
f(1,c)
f(2,c) f(2,c-w1)
f(5,c)
f(5,c-w1 –w3 –w4)
Integer Weights Dictionary
0 1 2 3 4 5 6 7 8
f[i][y]
5
4 i
3
2
1
y
Compute f[5][*]
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,7,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 i
3
2
1
y
Compute f[4][*]
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9 9 12 i
3
2
1
y
f(i,y) = max{f(i+1,y), f(i+1,y-wi) + pi}, y >= wi
Compute f[3][*]
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9 9 12 i
3 0 0 3 3 3 10 10 13 13
2
1
y
f(i,y) = max{f(i+1,y), f(i+1,y-wi) + pi}, y >= wi
Compute f[2][*]
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1
y
f(i,y) = max{f(i+1,y), f(i+1,y-wi) + pi}, y >= wi
Compute f[1][c]
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f(i,y) = max{f(i+1,y), f(i+1,y-wi) + pi}, y >= wi
Traceback
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f[1][8] = f[2][8] => x1 = 0
Traceback
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f[2][8] != f[3][8] => x2 = 1
Traceback
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f[3][5] != f[4][5] => x3 = 1
Traceback
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f[4][0] = f[5][0] => x4 = 0
Traceback
• n = 5, c = 8, w = [4,3,5,6,2], p = [9,8,10,9,3]
0 1 2 3 4 5 6 7 8
f[i][y]
5 0 0 3 3 3 3 3 3 3
4 0 0 3 3 3 3 9
9 12 i
3 0 0 3 3 3 10 10 13 13
2 0 0 3 8 8 11 11 13 18
1 18
y
f[5][0] = 0 => x5 = 0
Complexity Of Traceback
• O(n)
Matrix Multiplication Chains
• Multiply an m x n matrix A and an n x p matrix
B to get an m x p matrix C.
n
C(i,j) = A(i,k) * B(k,j)
k=1
• We shall use the number of multiplications as
our complexity measure.
• n multiplications are needed to compute one
C(i,j).
• mnp multiplicatons are needed to compute all
mp terms of C.
Matrix Multiplication Chains
• Suppose that we are to compute the product X*Y*Z of
three matrices X, Y and Z.
• The matrix dimensions are:
X:(100 x 1), Y:(1 x 100), Z:(100 x 1)
• Multiply X and Y to get a 100 x 100 matrix T.
100 * 1 * 100 = 10,000 multiplications.
• Multiply T and Z to get the 100 x 1 answer.
100 * 100 * 1 = 10,000 multiplications.
• Total cost is 20,000 multiplications.
• 10,000 units of space are needed for T.
Matrix Multiplication Chains
• The matrix dimensions are:
X:(100 x 1)
Y:(1 x 100)
Z:(100 x 1)
• Multiply Y and Z to get a 1 x 1 matrix T.
1 * 100 * 1 = 100 multiplications.
• Multiply X and T to get the 100 x 1 answer.
100 * 1 * 1 = 100 multiplications.
• Total cost is 200 multiplications.
• 1 unit of space is needed for T.
Product Of 5 Matrices
• M1x M2 x M3 x … x Mq
• Determine the q-1 matrix products in
reverse order.
What is the last multiplication?
What is the next to last multiplication?
And so on.
Problem State
• M1x M2 x M3 x … x Mq
• The matrices involved in each multiplication are a
contiguous subset of the given q matrices.
• The problem state is given by a set of pairs of the
form (i, j), i <= j.
The pair (i,j) denotes a problem in which the matrix
product Mix Mi+1 x … x Mj is to be computed.
The initial state is (1,q).
If the last matrix product is (M1x M2 x … x Mk) x (Mk+1x
Mk+2 x … x Mq), the state becomes {(1,k), (k+1,q)}.
Verify Principle Of Optimality
• Let Mij= Mi x Mi+1 x … x Mj, i <= j.
• Suppose that the last multiplication in the
best way to compute Mijis Mikx Mk+1,j for
some k, i <= k < j.
• Irrespective of what k is, a best computation
of Mijin which the last product is Mikx
Mk+1,j has the property that Mikand Mk+1,j
are computed in the best possible way.
• So the principle of optimality holds and
dynamic programming may be applied.
Recurrence Equations
• Let c(i,j) be the cost of an optimal (best) way to
compute Mij, i <= j.
• c(1,q) is the cost of the best way to multiply the
given q matrices.
• Let kay(i,j) = k be such that the last product in
the optimal computation of Mij is Mikx Mk+1,j.
• c(i,i) = 0, 1 <= i <= q. (Mii= Mi)
• c(i,i+1) = riri+1ri+2, 1 <= i < q. (Mii+1= Mix Mi+1)
• kay(i,i+1) = i.
c(i, i+s), 1 < s < q
• The last multiplication in the best way to
compute Mi,i+s is Mikx Mk+1,i+s for some k, i <= k
< i+s.
• If we knew k, we could claim:
c(i,i+s) = c(i,k) + c(k+1,i+s) + rirk+1ri+s+1
• Since i <= k < i+s, we can claim
c(i,i+s) = min{c(i,k) + c(k+1,i+s) + rirk+1ri+s+1}, where
the min is taken over i <= k < i+s.
• kay(i,i+s) is the k that yields above min.
Recurrence Equations
• c(i,i+s) =
min i <= k < i+s{c(i,k) + c(k+1,i+s) +
rirk+1ri+s+1}
• c(*,*) terms on right side involve fewer matrices
than does the c(*,*) term on the left side.
• So compute in the order s = 2, 3, …, q-1.
Recursive Implementation
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 100 0 1
0 10 0 2
0 100 0 3
0 0
0 100 0 1
0 10 0 2
0 100 0 3
0 0
i j
<k
i j
Recurrence For c(i,j,k) ), k > 0
• Shortest path goes through vertex k.
k
i j
k
i j
k
i j
i j
(i,j)
row k
2
9 6
1
5 3
9 1
1 2
7 7 4 5 1
4 8 4
2 4 7
5 16
• d(s,0) = 0.
• d(v,0) = infinity for v != s.
Recurrence For d(*,k), k > 0
s w v
Source vertex is 1.
Example
1
-6 6
1
3 2
4 6
7
5 3
3
4 5
9
1 2 3 4 5 6 v
0 0 - - - - - - - - - - - k
1 0 3 - 7 - - - 1 - 1 - -
2 0 3 7 7 16 8 - 1 2 1 4 4
3 0 2 7 7 10 8 - 6 2 1 3 4
4 0 2 6 7 10 8 - 6 2 1 3 4
d(v,k) p(v.k)
Example
1
-6 6
1
3 2
4 6
7
5 3
3
4 5
9
1 2 3 4 5 6 v
4 0 2 6 7 10 8 - 6 2 1 3 4 k
5 0 2 6 7 9 8 - 6 2 1 3 4
d(v,k) p(v.k)
Shortest Path From 1 To 5
1
-6 6
1
3 2
4 6
7
5 3
3
4 5
9
1 2 3 4 5 6 1 2 3 4 5 6
5 0 2 6 7 9 8 - 6 2 1 3 4
d(v,5) p(v,5)
Observations
• d(v,k) = min{d(v,0),
min{d(w,k-1) + length of edge (w,v)}}
• d(s,k) = 0 for all k.
• If d(v,k) = d(v,k-1) for all v, then d(v,j) = d(v,k-1),
for all j >= k-1 and all v.
– i.e. the shortest path uses k-1 edges
• If we stop computing as soon as we have a d(*,k)
that is identical to d(*,k-1) the run time becomes
O(n3) when adjacency matrix is used.
O(ne) when adjacency lists are used.
Observations
• The computation may be done in-place.
d(v) = min{d(v), min{d(w) + length of edge (w,v)}}
instead of
d(v,k) = min{d(v,0),
min{d(w,k-1) + length of edge (w,v)}}
• Following iteration k, d(v,k+1) <= d(v) <= d(v,k)
• On termination d(v) = d(v,n-1).
• Space requirement becomes O(n) for d(*) and
p(*).
Applications
encryption
message encryption key
algorithm
Transmission
Channel
decryption
decryption key message
algorithm
Public Key Cryptosystem (RSA)
• Message M < n.
• Encryption key = (a,n).
• Decryption key = (b,n).
• Encrypt => E = Ma mod n.
• Decrypt => M = Eb mod n.
Breaking RSA
• Partition
Partition n positive integers s1, s2, s3, …, sn into
two groups A and B such that the sum of the
numbers in each group is the same.
[9, 4, 6, 3, 5, 1,8]
A = [9, 4, 5] and B = [6, 3, 1, 8]
• NP-hard.
Subset Sum Problem
Home city
Visit city
Applications Of TSP
Robot Station
Applications Of TSP
• Manufacturing.
• A robot arm is used to drill n holes in a metal
sheet.
Robot Station
8x8 Chessboard
n-Queens Problem
Can n queens be placed on an n x n
chessboard so that no queen may attack
another queen?
4x4
n-Queens Problem
8x8
Difficult Problems
x1=1 x1= 0
x3=1 x3= 0
x4=1 x4=0
x1=1 x1= 3
x1=2
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
x1=1 x1= 0
4 14 1 1 2 3 4
13 2 3 12 5 6 7 8
6 11 5 10 9 10 11 12
9 8 7 15 13 14 15
Branch And Bound
FIFO branch and bound finds solution closest to root.
Backtracking may never find a solution because tree
depth is infinite (unless repeating configurations are
eliminated).
• Least-cost branch and bound directs the search to
parts of the space most likely to contain the
answer. So it could perform better than
backtracking.
Branch And Bound
• maintain provable lower and upper bounds on
global objective value
– terminate with certificate proving epsilon–sub
optimality
• rely on two subroutines that (efficiently) compute
a lower and an upper bound on the optimal value
over a given region of search space
• often slow; exponential worst case performance