ADA - Module 3
ADA - Module 3
For example, for the pattern BARBER, all the table’s entries will be equal to 6, except for the entries for E, B, R,
and A, which will be 1, 2, 3, and 4, respectively.
Horspool’s Algorithm
Initialize all the entries to the pattern’s length m and scan the pattern left to right repeating the following step
m − 1 times: for the jth character of the pattern (0 ≤ j ≤ m − 2), overwrite its entry in the table with m − 1− j ,
which is the character’s distance to the last character of the pattern.
Module 3
Transform and Conquer.
By
Kavyashree G M
Assistant Professor
ISE, DSATM
Heaps and Heapsort
• priority queue is a multiset of items with an orderable characteristic
called an item’s priority, with the following operations:
For example, consider the trees of Figure 6.9. The first tree is a heap. The second one is not a heap, because the
tree’s shape property is violated. And the third one is not a heap, because the parental dominance fails for the node
with key 5.
Properties of heap
Construction of heap
The first is the bottom-up heap construction algorithm illustrated in Figure 6.11. It
initializes the essentially complete binary tree with n nodes by placing keys in the
order given and then “heapifies” the tree as follows.
• Starting with the last parental node, the algorithm checks whether
the parental dominance holds for the key in this node.
• If it does not, the algorithm exchanges the node’s key K with the
larger key of its children and checks whether the parental dominance
holds for K in its new position. This process continues until the
parental dominance for K is satisfied
top-down heap construction algorithm
• The alternative (and less efficient) algorithm constructs a heap by
successive insertions of a new key into a previously constructed heap;
• we insert a new key K into a heap? First, attach a new node with key K
in it after the last leaf of the existing heap.
• Then shift K up to its appropriate place in the new heap as follows:
Compare K with its parent’s key: if the latter is greater than or equal to
K, stop (the structure is a heap); otherwise, swap these two keys and
compare K with its new parent.
This swapping continues until K is not greater than its last parent or it
reaches the root (illustrated in Figure 6.12).
• Since the height of a heap with n nodes is about log2 n, the time
efficiency of insertion is in O(log n).
How can we delete an item from a heap? We consider here only the most Deleting
the root’s key from a heap can be done with the following algorithm, illustrated in
Figure 6.13.important case of deleting the root’s key,
HeapSort