CSC 8301-Design and Analysis of Algorithms
CSC 8301-Design and Analysis of Algorithms
CSC 8301-Design and Analysis of Algorithms
Lecture 7
1
10/31/16
Presorting
q sorting ahead of time, to make repetitive solutions faster
Many problems involving lists are easier when list is sorted, e.g.,
q searching
Also:
q Topological sorting helps solving some problems for dags
2
10/31/16
Presorting-based algorithm:
Stage 1 Sort the array by, say, mergesort
Stage 2 Apply binary search
Good or bad?
Why do we have our dictionaries, telephone directories, etc. sorted?
3
10/31/16
Efficiency: O(n2)
q Add the above equation to the 2nd one in the system
(a22-a21a12/a11)x2 = b2–a21b1/a11
4
10/31/16
Solve the latter by substitutions starting with the last equation and
moving up to the first one.
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
5
10/31/16
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
6
10/31/16
Representation Change
Searching Problem
Problem: Given a (multi)set S of keys and a search
key K, find an occurrence of K in S, if any
7
10/31/16
q Hashing
– open hashing (separate chaining)
– closed hashing (open addressing)
<K >K
8
10/31/16
q to allow more than one key per node of a search tree
– 2-3 trees
– 2-3-4 trees
– B-trees
9
10/31/16
10 10
0 1 0 0
5 20 5 20
1 -1 0 1 -1
4 7 12 4 7
0 0 0 0
2 8 2 8
(a) (b)
Rotations
1 0 0 -1 0 0
R LR
2 > 1 3 1 > 1 3
0 0
1 2
(a) (c)
10
10/31/16
11
10/31/16
0
8
1 2 1
6 6 6
1 0 2 0 R (5) 0 0
5 8 5 8 > 3 8
0 1 0 0
3 3 2 5
0
2
12
10/31/16
0 1 0 0 0
2 5 2 4 8
0
4
-1 0
5 5
0 -2 0 0
3 6 3 7
RL (6)
0 0 1 > 0 0 0 0
2 4 8 2 4 6 8
0
7
q Disadvantages:
– frequent rotations
– complexity
13
10/31/16
2-3 Tree
Definition A 2-3 tree is a search tree that
q may have 2-nodes and 3-nodes
2-node 3-node
K K1, K2
14
10/31/16
8
8 3,
3, 8
8 3,
3, 8
8
>
2,
2, 3,
3, 5
5 9
9 2
2 5
5 9
9 2
2 4,
4, 5
5 9
9
5
5
3,
3, 8
8 > 3,
3, 5,
5, 8
8 >
3
3 8
8
2
2 4,
4, 5,
5, 7
7 9
9 2
2 4
4 7
7 9
9 2
2 4
4 7
7 9
9
❂ log3 (n + 1) - 1 ≤ h ≤ log2 (n + 1) - 1
15
10/31/16
Homework
16