CH 07
CH 07
CH 07
prestructuring
hashing
indexing schemes (eg, B-trees)
Sorting by Counting
Algorithm ComparisonCountingSort(A[0..n-1])
for i 0 to n-1 do Count[i] 0
for i 0 to n-2 do
for j i+1 to n-1 do
if A[i] <A[j] then Count[j] Count[j]+1
else Count[i] Count[i]+1
for i 0 to n-1 do S[Count[i]] A[i]
Example: 62 31 84 96 19 47
Efficiency
Design and Analysis of Algorithms - Chapter 7
String matching
3. while pattern is not found and the text is not yet exhausted,
realign pattern one position to the right and repeat step 2.
Horspools Algorithm
Shift table
Algorithm ShiftTable(P[0..m-1])
for i 0 to size-1 do Table[i] m
for j 0 to m-2 do Table[P[j]] m-1-j
return Table
Design and Analysis of Algorithms - Chapter 7
Shift table
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
Then:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
The Algorithm
Horspool Matching(P[0..m-1,T[0..n-1]])
ShiftTable(P[0..m-1])
i m-1
while i<=n-1 do
k 0
while k<=m-1 and P[m-1-k]=T[i-k] do
k k+1
if k=m return i-m+1
else i i+Table[T[i]]
return -1
Design and Analysis of Algorithms - Chapter 7
10
Boyer-Moore algorithm
11
12
13
14
pattern
d2
pattern
d2
1 ABCBAB 2
1 BAOBAB 2
2 ABCBAB 4
2 BAOBAB 5
3 ABCBAB 4
3 BAOBAB 5
4 ABCBAB 4
4 BAOBAB 5
5 ABCBAB 4
5 BAOBAB 5
15
Calculate shift as
d1 if k=0
d=
max(d1,d2) if k>0
where d1=max(t1(c)-k)
Example
BESS_KNEW_ABOUT_BAOBABS
BAOBAB
Design and Analysis of Algorithms - Chapter 7
16
Hashing
find
delete
Applications:
databases
symbol tables
Design and Analysis of Algorithms - Chapter 7
17
be easy to compute
distribute keys evenly throughout the table
18
Collisions
19
Open hashing
If hash function distributes keys uniformly,
average length of linked list will be n/m
Average number of probes S = 1+/2, U =
Worst-case is still linear!
Open hashing still works if n>m.
20
Closed hashing
21