Download Full (Ebook) A Textbook of Data Structures and Algorithms, Volume 3 : Mastering Advanced Data Structures and Algorithm Design Strategies by G. A. Vijayalakshmi Pai ISBN 9781786308924, 1786308924 PDF All Chapters
Download Full (Ebook) A Textbook of Data Structures and Algorithms, Volume 3 : Mastering Advanced Data Structures and Algorithm Design Strategies by G. A. Vijayalakshmi Pai ISBN 9781786308924, 1786308924 PDF All Chapters
com
OR CLICK HERE
DOWLOAD EBOOK
ebooknice.com
https://ebooknice.com/product/data-structures-and-algorithm-analysis-
in-java-2612714
ebooknice.com
https://ebooknice.com/product/data-structures-and-algorithm-analysis-
in-java-3rd-edition-2391666
ebooknice.com
https://ebooknice.com/product/data-structures-and-algorithm-analysis-
in-c-3rd-edition-2384264
ebooknice.com
ebooknice.com
https://ebooknice.com/product/a-common-sense-guide-to-data-structures-
and-algorithms-7118874
ebooknice.com
ebooknice.com
A Textbook of Data Structures and Algorithms 3
One of the greatest lessons I have learnt in my life is
to pay as much attention to the means of work as to its end…
I have been always learning great lessons from that one principle,
and it appears to me that all the secret of success is there;
to pay as much attention to the means as to the end….
Let us perfect the means; the end will take care of itself.
– Swami Vivekananda
(Lecture Delivered at Los Angeles, California, January 4, 1900)
A Textbook of Data
Structures and Algorithms 3
G A Vijayalakshmi Pai
First published 2022 in Great Britain and the United States by ISTE Ltd and John Wiley & Sons, Inc.
Previous edition published in 2008 as “Data Structures and Algorithms: Concepts, Techniques and
Applications” by McGraw Hill Education (India) Pvt Ltd. © McGraw Hill Education (India) Pvt Ltd.
2008
Apart from any fair dealing for the purposes of research or private study, or criticism or review, as
permitted under the Copyright, Designs and Patents Act 1988, this publication may only be reproduced,
stored or transmitted, in any form or by any means, with the prior permission in writing of the publishers,
or in the case of reprographic reproduction in accordance with the terms and licenses issued by the
CLA. Enquiries concerning reproduction outside these terms should be sent to the publishers at the
undermentioned address:
www.iste.co.uk www.wiley.com
Any opinions, findings, and conclusions or recommendations expressed in this material are those of the
author(s), contributor(s) or editor(s) and do not necessarily reflect the views of ISTE Group.
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Most of the well-known text books/monographs on this subject have discussed the
concepts in relation to a programming language – beginning with Pascal and spanning
a spectrum of them such as C, C++, C#, Java, Python and so on, essentially calling for
ample knowledge of the language, before one proceeds to try and understand the
data structure. There does remain a justification in this. The implementation of data
structures in the specific programming language need to be demonstrated or the
algorithms pertaining to the data structures concerned need a convenient medium of
presentation and when this is the case, why not a programming language?
Again, while some authors have insisted on using their books for an advanced
level course, there are some who insist on a working knowledge of the specific
programming language as a prerequisite to using the book. However, in the case of a
core course, as it is in most academic programs, it is not uncommon for a novice or a
sophomore to be bewildered by the “miles of code” that demonstrate or explain a
data structure, rendering the subject difficult to comprehend. In fact, the efforts that
one needs to put in to comprehend the data structure and its applications are
xii A Textbook of Data Structures and Algorithms 3
This means that text books catering to the fundamental understanding of the data
structure concepts for use as course material in the classroom are as much needed as
the books that cater to the implementation of data structures in a programming
language for use in the laboratory sessions. While most books in the market conform
to the latter, bringing out a book to be classroom course material and used by
instructors handling a course on data structures and algorithms, comprehensive
enough for the novice students to benefit from, has been the main motivation in
writing this book.
As such, the book details concepts, techniques and applications pertaining to data
structures and algorithms, independent of any programming language, discusses
Preface xiii
several examples and illustrative problems, poses review questions to reinforce the
understanding of the theory, and presents a suggestive list of programming
assignments to aid implementation of the data structures and algorithms learned.
In fact, the book may either be independently used as a textbook since it is self-
contained or serve as a companion for books discussing data structures and
algorithms implemented in specific programming languages such as C, C++, Java,
Python, and so on.
– Skip list search, counting sort and bucket sort have been included in the
chapters on searching and sorting algorithms in Volume 3.
– The algorithm design techniques of divide and conquer, the greedy method
and dynamic programming have been elaborately discussed in Chapters 19–21 in
Volume 3.
– The concept of NP-completeness has been detailed in a newly included
chapter, Chapter 22 in Volume 3.
– Several illustrative problems, review questions and programming assignments
have been added to enrich the content and aid in understanding the concepts. The
new edition thus includes 181 illustrative problems, 276 review questions and 108
programming assignments.
The book comprises three volumes, namely, Volume 1: Chapters 1–7, Volume 2:
Chapters 8–12 and Volume 3: Chapters 13–22.
Chapters 3–5 detail sequential linear data structures, namely, arrays, strings, bit
arrays, stacks, queues, priority queues and dequeues, and their applications.
Chapters 6 and 7 elucidate linked linear data structures, namely linked lists, linked
stacks and linked queues, and their applications.
Chapters 13–15 discuss hash tables, files, k-d trees and treaps. Chapter 16
discusses the search algorithms of linear search, transpose sequential search,
interpolation search, binary search, Fibonacci search, skip list search and other
search techniques.
Preface xv
Chapters 19–21 detail the algorithm design strategies of divide and conquer, the
greedy method and dynamic programming and their applications.
For a full list of the contents of Volumes 1 and 2, see the summary at the end of
this book.
Target audience
An advanced level course that focuses on advanced data structures and algorithm
design could begin with a review of Chapter 8 and include Chapters 9–12 of Volume 2,
Chapters 14 and 15 and selective sections of Chapters 16–18, and Chapters 19–22 of
Volume 3 in its curriculum based on the level of prerequisite courses satisfied.
Chapters 8–10 and Chapter 11 (sections 11.1–11.3) of Volume 2 and Chapters 13,
14 and 18 of Volume 3 could be useful to include in a curriculum that serves as a
prerequisite for a course on database management systems.
The author is grateful to ISTE Ltd., London, UK, for accepting to publish the
book, in collaboration with John Wiley & Sons Inc., USA. She expresses her
appreciation to the publishing team, for their professionalism and excellent
production practices, while bringing out this book in three volumes.
The author expresses her sincere thanks to the Management and Principal, PSG
College of Technology, Coimbatore, India for the support extended while writing
the book.
The author would like to place on record her immense admiration and affection
for her father, Late Professor G. A. Krishna Pai and her mother Rohini Krishna Pai
for their unbounded encouragement and support to help her follow her life lessons
and her sisters Dr. Rekha Pai and Udaya Pai, for their unstinted, anywhere-anytime-
anything kind of help and support, all of which were instrumental and inspirational
in helping this author create this work.
G. A. Vijayalakshmi Pai
August 2022
13
Hash Tables
13.1. Introduction
The data structures of binary search trees, AVL trees, B trees, tries, red-black
trees and splay trees discussed so far in the book (Volume 2) are tree-based data
structures. These are nonlinear data structures and serve to capture the hierarchical
relationship that exists between the elements forming the data structure. However,
there are applications that deal with linear or tabular forms of data, devoid of any
superior-subordinate relationship. In such cases, employing these data structures
would be superfluous. Hash tables are one among such data structures which favor
efficient storage and retrieval of data elements that are linear in nature.
13.1.1. Dictionaries
Hash tables are ideal data structures for dictionaries. In this chapter, we
introduce the concept of hashing and hash functions. The structure and operations of
the hash tables are also discussed. The various methods of collision resolution, for
example, linear open addressing and chaining and their performance analyses are
detailed. Finally, the application of hash tables in the fields of compiler design,
relational database query processing and file organization are discussed.
When the data elements of the dictionary are to be stored in the hash table, each
key Xi is mapped to a position Pi in the hash table as determined by the value of
H(Xi), that is, Pi = H(Xi). To search for a key X in the hash table all that one does is
determine the position P by computing P = H(X) and accessing the appropriate data
element. In the case of insertion of a key X or its deletion, the position P in the hash
table where the data element needs to be inserted or from where it is to be deleted
respectively, is determined by computing P = H(X).
If the hash table is implemented using a sequential data structure, for example,
arrays, then the hash function H(X) may be so chosen to yield a value that
corresponds to the index of the array. In such a case the hash function is a mere
mapping of the keys to the array indices.
Hash Tables 3
EXAMPLE 13.1.–
H(XYmn) = ord(X)
where X, Y are the alphabetical characters, m, n are the numerical characters of the
key, and ord(X) is the ordinal number of the alphabet X.
The computations of the positions of the keys in the hash table are shown below:
The hash table accommodating the data elements appears as shown below:
1 AB12 ……….
2 ….
3 CG45
4 ….
5 EX44 ………
…. …..
11 KL78
…
15 OW31 ………….
…
18 RK32
19 ST65 ……………
….
22 VP99 ….
… … …
4 A Textbook of Data Structures and Algorithms 3
In Example 13.1, it was assumed that the hash function yields distinct values for
the individual keys. If this were to be followed as a criterion, then the situation may
turn out of control since, in the case of dictionaries with a very large set of data
elements, the hash table size can be too huge to be handled efficiently. Therefore, it
is convenient to choose hash functions that yield values lying within a limited range
so as to restrict the length of the table. This would consequently imply that the hash
functions may yield identical values for a set of keys. In other words, a set of keys
could be mapped to the same position in the hash table.
Let X1, X2, ….Xn be the n keys that are mapped to the same position P in the hash
table. Then, H(X1) = H(X2) = …H(Xn) = P. In such a case, X1, X2, ….Xn are called
synonyms. The act of two or more synonyms vying for the same position in the hash
table is known as a collision. Naturally, this entails a modification in the structure of
the hash table to accommodate the synonyms. The two important methods of linear
open addressing and chaining to handle synonyms are presented in sections 13.4 and
13.5, respectively.
The choice of the hash function plays a significant role in the structure and
performance of the hash table. It is therefore essential that a hash function satisfies
the following characteristics:
i) easy and quick to compute;
ii) even distribution of keys across the hash table. In other words, a hash function
must minimize collisions.
result yields 98 which is chosen as the index of the hash table where the key 719532
is to be accommodated.
ii) Truncation: In this method, the selective digits of the key are extracted to
determine the index of the hash table where the key needs to be accommodated. In
the case of alphabetical keys, their numerical equivalents may be considered.
Truncation though quick to compute does not ensure even distribution of keys.
iii) Modular arithmetic: This is a popular method and the size of the hash table
L is involved in the computation of the hash function. The function makes use of
modulo arithmetic. Let k be the numerical key or the numerical equivalent if it is an
alphabetical key. The hash function is given by
H(k) = k mod L
The hash function evidently returns a value that lies between 0 and L-1.
Choosing L to be a prime number has a proven better performance by way of even
distribution of keys.
EXAMPLE 13.2.–
Let us consider a set of keys {45, 98, 12, 55, 46, 89, 65, 88, 36, 21} to be
represented as a hash table as shown in Figure 13.2. Let us suppose the hash
function H is defined as H(X) = X mod 11. The hash table, therefore, has 11 buckets.
We propose three slots per bucket. Table 13.1 shows the hash function values of the
keys and Figure 13.3 shows the structure of the hash table.
Key X 45 98 12 55 46 89 65 88 36 21
H(X) 1 10 1 0 2 1 10 0 3 10
Observe how keys {45, 12, 89}, {98, 65, 21} and {55, 88} are synonyms
mapping to the same bucket 1, 10 and 0 respectively.The provision of three slots per
bucket makes it possible to accommodate synonyms.
Hash Tables 7
Now, what happens if a synonym is unable to find a slot in the bucket? In other
words, if the bucket is full, then where do we find a place for the synonyms? In such
a case an overflow is said to have occurred. All collisions need not result in
overflows. But in the case of a hash table with single slot buckets, collisions mean
overflows.
The bucket to which the key is mapped by the hash function is known as the
home bucket. To tackle overflows we move further down, beginning from the home
bucket and look for the closest slot that is empty and place the key in it. Such a
method of handling overflows is known as Linear probing or Linear open
addressing or closed hashing.
EXAMPLE 13.3.–
Let us proceed to insert the keys {77, 34, 43} in the hash table discussed in
Example 13.2. The hash function values of the keys are {0, 1, 10}. When we
proceed to insert 77 in its home bucket 0, we find a slot is available and hence the
insertion is done. In the case of 34, its home bucket 1 is full and hence there is an
overflow. By linear probing, we look for the closest slot that is vacant and find one
in the second slot of bucket 2. While inserting 43, we find bucket 10 to be full.
8 A Textbook of Data Structures and Algorithms 3
The search for the closest empty slot proceeds by moving downward in a circular
fashion until it finds a vacant place in slot 3 of bucket 2. Note the circular movement
of searching the hash table while looking for an empty slot. Figure 13.3 illustrates
the linear probing method undertaken for the listed keys. The keys which have been
accommodated in places other than their home buckets are shown over grey
background.
Search: Searching for a key in a linear open addressed hash table proceeds on
lines similar to that of insertion. However, if the searched key is available in the
home bucket then the search is done. The time complexity in such a case is O(1).
However, if there had been overflows while inserting the key, then a sequential
search has to be called which searches through each slot of the buckets following the
home bucket until either (i) the key is found or (ii) an empty slot is encountered in
which case the search terminates or (iii) the search path has curled back to the home
bucket. In the case of (i), the search is said to be successful. In the cases of (ii) and
(iii), it is said to be unsuccessful.
EXAMPLE 13.4.–
Consider the snapshot of the hash table shown in Figure 13.5, which represents
keys whose first character lies between ‘A’ and ‘I’, both inclusive. The hash
Hash Tables 9
function used is H(X) = ord(C) mod 10 where C is the first character of the
alphabetical key X.
The search for keys F18 and G64 is straightforward since they are present in
their home buckets, which are 6 and 7, respectively. The search for keys A91 and
F78 for example, are slightly more involved, in the sense that though they are
available in their respective home buckets they are accessed only after a sequential
search for them is done in the slots corresponding to their buckets. On the other
hand, the search for I99 fails to find it in its home bucket, which is 9. This, therefore,
triggers a sequential search of every slot following the home bucket until the key is
found, in which case the search is successful or until an empty slot is encountered, in
which case the search is a failure. I99 is indeed found in slot 2 of bucket 2! Observe
how the search path curls back to the top of the hash table from the home bucket of
key I99. Let us now search for the key G93. The search proceeds to look into its
home bucket (7) before a sequential search for the same is undertaken in the slots
following the home bucket. The search stops due to its encountering an empty slot
and therefore the search is deemed unsuccessful.
Algorithm 13.1 illustrates the search algorithm for a linear open addressed hash
table.
10 A Textbook of Data Structures and Algorithms 3
Insert: the insertion of data elements in a linear open addressed hash table is
executed as explained in the previous section. The hash function, which is quite
often modulo arithmetic based, determines the bucket b and thereafter slot s in
which the data element is to be inserted. In the case of overflow, we search for the
closest empty slot beginning from the home bucket and accommodate the key in the
slot. Algorithm 13.1 could be modified to execute the insert operation. The line
Delete: the delete operation on a hash table can be clumsy. When a key is
deleted it cannot be merely wiped off from its bucket (slot). A deletion leaves the
slot vacant and if an empty slot is chosen as a signal to terminate a search then many
of the elements following the empty slot and displaced from their home buckets may
go unnoticed. To tackle this it is essential that the keys following the empty slot be
moved up. This can make the whole operation clumsy.
An alternative could be to write a special element in the slot every time a delete
operation is done. This special element not only serves to camouflage the empty
space ‘available’ in the deleted slot when a search is in progress but also serves to
accommodate an insertion when an appropriate element assigned to the slot turns up.
The complexity of the linear open addressed hash table is dependent on the
number of buckets. In the case of hash functions that follow modular arithmetic, the
number of buckets is given by the divisor L.
The best case time complexity of searching for a key in a hash table is given by
O(1) and the worst case time complexity is given by O(n), where n is the number of
data elements stored in the hash table. A worst case occurs when all the n data
elements map to the same bucket.
Hash Tables 11
The time complexities when compared to those of their linear list counterparts
are not in any way less. The best and worst case complexity of searching for an
element in a linear list of n elements is respectively, O(1) and O(n). However, on
average, the performance of the hash table is much more efficient than that of the
linear lists. It has been shown that the average case performance of a linear open
addressed hash table for an unsuccessful and successful search is given by
𝑈 ~ 1+
( )
𝑆 ~ 1+
( )
Thus, rehashing makes use of at least two functions H, H’ where H(X), H’(X)
map keys X to any one of the b buckets. To insert a key, H(X) is computed and the
key X is accommodated in the bucket if it is empty. In the case of a collision, the
second hash function H’(X) is computed and the search sequence for the empty slot
proceeds by computing,
procedure LOP_HASH_SEARCH(HT, b, s X)
/* HT[0:b-1, 0:s-1] is the hash table implemented as a
two dimensional array. Here b is the number of buckets
and s is the number of slots. X is the key to be
searched in the hash table. In case of unsuccessful
search, the procedure prints the message “KEY not
found” otherwise prints “KEY found”*/
end LOP_HASH_SEARCH
Here, h1, h2, ... is the search sequence before an empty slot is found to
accommodate the key. It needs to be ensured that H’(X) does not evaluate to 0, since
there is no way this would be of help. A good choice for H’(X) is given by
M – (X mod M) where M is chosen to be a prime smaller than the hash table size
(see illustrative problem 13.6)
This is another method that can substantially reduce clustering. In this method
when a collision occurs at address h, unlike linear probing which probes buckets in
Hash Tables 13
locations h+1, h+2 …. and so forth, the technique probes buckets at locations h+1,
h+4, h+9,…. and so forth. In other words, the method probes buckets at locations
(ℎ + 𝑖 ) 𝑚𝑜𝑑 𝑏, 𝑖 = 1, 2, . . . ., where h is the home bucket and b is the number
of buckets. However, there is no guarantee that the method gives a fair chance to
probe all locations in the hash table. Though quadratic probing reduces primary
clustering, it may result in probing the same set of alternate cells. Such a case known
as secondary clustering occurs especially when the hash table size is not prime.
If b is a prime number then quadratic probing probes exactly half the number of
locations in the hash table. In this case, the method is guaranteed to find an empty
slot if the hash table is at least half empty (see illustrative problems 13.4 and 13.5).
Unlike quadratic probing where the increment during probing was definite,
random probing makes use of a random number generator to obtain the increment
and hence the next bucket to be probed. However, it is essential that the random
number generator function generates the same sequence. Though this method
reduces clustering, it can be a little slow when compared to others.
13.5. Chaining
An alternative to overcome this malady is to keep all synonyms that are mapped
to the same bucket chained to it. In other words, every bucket is maintained as a
singly linked list with synonyms represented as nodes. The buckets continue to be
represented as a sequential data structure as before, to favor the hash function
computation. Such a method of handling overflows is called chaining or open
hashing or separate chaining. Figure 13.6 illustrates a chained hash table.
14 A Textbook of Data Structures and Algorithms 3
In the figure, observe how the buckets have been represented sequentially and
each of the buckets is linked to a chain of nodes which are synonyms mapping to the
same bucket.
Chained hash tables only acknowledge collisions. There are no overflows per se
since any number of collisions can be handled provided there is enough memory to
handle them!
EXAMPLE 13.5.–
Let us consider the set of keys {45, 98, 12, 55, 46, 89, 65, 88, 36, 21} listed in
Example 13.2, to be represented as a chained hash table. The hash function H used is
H(X) = X mod 11. The hash function values for the keys are shown in Table 13.1.
The structure of the chained hash table is shown in Figure 13.7.
Observe how each of the groups of synonyms for example, {45, 12, 89}, {98, 65,
21} and {55, 88} are represented as singly linked lists corresponding to the buckets
1, 10 and 0 respectively. In accordance with the norms pertaining to singly linked
lists, the link field of the last synonym in each chain is a null pointer. Those buckets
which are yet to accommodate keys are also marked null.
Hash Tables 15
Search: The search for a key X in a chained hash table proceeds by computing
the hash function value H(X). The bucket corresponding to the value H(X) is
accessed and a sequential search along the chain of nodes is undertaken. If the key is
found then the search is termed successful otherwise unsuccessful. If the chain is too
long maintaining the chain in order (ascending or descending) helps in rendering the
search efficient.
Insert: To insert a key X into a hash table, we compute the hash function H(X) to
determine the bucket. If the key is the first node to be linked to the bucket then all
that it calls for is a mere execution of a function to insert a node in an empty singly
linked list. In the case of keys that are synonyms, the new key could be inserted
either at the beginning or the end of the chain leaving the list unordered. However, it
would be prudent and less expensive too, to maintain each of the chains in the
ascending or descending order of the keys. This would also render the search for a
specific key among its synonyms to be efficiently carried out.
EXAMPLE 13.6.–
Let us insert keys {76, 48} into the chained hash table shown in Figure 13.7.
Since 76 already has three synonyms in its chain corresponding to bucket 10, we
choose to insert it in order in the list. On the other hand, 48 is the first key in its
bucket, which is 4. Figure 13.8 illustrates the insertion.
procedure CHAIN_HASH_SEARCH(HT, b, X)
/* HT[0:b-1] is the hash table implemented as a one
dimensional array of pointers to buckets. Here b is the number
of buckets. X is the key to be searched in the hash table. In
case of unsuccessful search, the procedure prints the message
“KEY not found” otherwise prints “KEY found”*/
Algorithm 13.2 could be modified to insert a key. It merely calls for the insertion
of a node in a singly linked list that is unordered or ordered.
Delete: Unlike that of linear open addressed hash tables, the deletion of a key X
in a chained hash table is elegantly done. All that it calls for is a search for X in the
corresponding chain and deletion of the respective node.
The complexity of the chained hash table is dependent on the length of the chain
of nodes corresponding to the buckets. The best case complexity of a search is O(1).
A worst case occurs when all the n elements map to the same bucket and the length
of the chain corresponding to that bucket is n, with the searched key turning out
to be the last in the chain. The worst-case complexity of the search in such a case
is O(n).
( )
𝑈 ~ ,𝛼 ≥ 1
𝑆 ~1 +
The average case performance of the chained hash table is superior to that of the
linear open addressed hash table.
13.6. Applications
In this section, we discuss the application of hash tables in the fields of compiler
design, relational database query processing and file organization.
In section 10.4.1, (Volume 2) the application of binary search trees and AVL
trees for the representation of symbol tables in a compiler was discussed. Hash
tables find applications in the same problem as well.
EXAMPLE 13.7.–
the keyword set. Considering the efficient retrievals promoted by the hash table, the
choice of the data structure for the symbol table representation contributes to the
efficient performance of a compiler as well.
EXAMPLE 13.8.–
A query pertaining to who the vendors are for a given item code calls for joining
the two relations. The join of the two relations yields the relation shown in Figure
13.10(b). Observe how the natural join operation combines the two relations on the
basis of their common attribute ITEM_CODE. Those tuples (rows) of the two
relations having a common attribute value in the ITEM_CODE field are “joined”
together to form the output relation.
One method of evaluating a join is to use the hash method. Let H(X) be the hash
function where X is the attribute value of the relations. Here H(X) is the address of
the bucket which contains the attribute value and a pointer to the appropriate tuple
corresponding to the attribute value. The pointer to the tuple is known as Tuple
Identifier (TID). TIDs in general, besides containing the physical address of the
Hash Tables 21
tuple of the relation also hold identifiers unique to the relation. The hash tables are
referred to as hash indexes in relational database terminology.
A natural join of the two relations R and S over a common attribute ATTRIB,
results in each bucket of the hash indexes recording the attribute values of ATTRIB
along with the TIDs of the tuples in relations R and S whose R.ATTRIB =
S.ATTRIB.
When a query associated with the natural join is to be answered all that it calls
for is to access the hash indexes to retrieve the appropriate TIDs associated with the
query. Retrieving the tuples using the TIDs satisfies the query.
EXAMPLE 13.9.–
Assume that a query “List the vendor(s) supplying the item P402” is to be
processed. To process this request, we first compute H(“P402”) which as shown in
Figure 13.11(b) yields the bucket address 16. Accessing bucket 16 we find the TID
corresponding to the relation VENDOR is 7001. To answer the query all that needs
to be done is to retrieve the tuple whose TID is 7001.
A general query such as “List the vendors supplying each of the items” may call
for sequentially searching each of the hash indexes corresponding to each attribute
value of ITEM_CODE.
22 A Textbook of Data Structures and Algorithms 3
The direct file organization (see section 14.8) which is a kind of file organization
method, employs hash tables for the efficient storage and retrieval of records from
the storage devices. Given a file of records, { f1, f2, f3,……fN} with keys { k1, k2,
k3,…kN} a hash function H(k) where k is the record key, determines the storage
address of each of the records in the storage device. Thus, direct files undertake
direct mapping of the keys to the storage locations of the records with the records of
the file organized as a hash table.
Hash Tables 23
Summary
– Hash tables are ideal data structures for dictionaries. They favor efficient storage and
retrieval of data lists which are linear in nature.
– A hash function is a mathematical function which maps keys to positions in the hash
tables known as buckets. The process of mapping is called hashing. Keys which map to
the same bucket are called as synonyms. In such a case a collision is said to have occurred.
A bucket may be divided into slots to accommodate synonyms. When a bucket is full and
a synonym is unable to find space in the bucket then an overflow is said to have occurred.
– The characteristics of a hash function are that it must be easy to compute and at the
same time minimize collisions. Folding, truncation and modular arithmetic are some of the
commonly used hash functions.
– A hash table could be implemented using a sequential data structure such as arrays.
In such a case, the method of handling overflows where the closest slot that is vacant is
utilized to accommodate the synonym key is called linear open addressing or linear
probing. However, over the course of time, linear probing can lead to the problem of
clustering thereby deteriorating the performance of the hash table to a mere sequential
search!
– The other alternative methods of handling overflows are rehashing, quadratic probing
and random probing.
– Hash tables have found applications in the design of symbol tables in compiler
design, query processing in relational database management systems and direct file
organizations.
PROBLEM 13.1.–
Insert the following data into a hash table implemented using linear open
addressing. Assume that the buckets have three slots each. Make use of the hash
function h(X) = X mod 9.
{17, 09, 34, 56, 11, 71, 86, 55, 22, 10, 4, 39, 49, 52, 82, 13, 40, 31, 35, 28, 44}
24 A Textbook of Data Structures and Algorithms 3
Solution:
The linear open addressed hash table is shown in Figure P13.1 Those keys not
accommodated in their home buckets are shown over a grey shaded background.
PROBLEM 13.2.–
For the set of keys listed in illustrative problem 13.1, trace a chained hash table
making use of the same hash function.
Solution:
The chained hash table is shown in Figure P13.2. The nodes in the chain are
inserted in ascending order of the key values.
PROBLEM 13.3.–
Solution:
No, this is illogical since increasing the number of buckets will only lead to the
wastage of space.
PROBLEM 13.4.–
For the set of keys {17, 9, 34, 56, 11, 4, 71, 86, 55, 10, 39, 49, 52, 82, 31, 13, 22,
35, 44, 20, 60, 28} obtain a hash table HT[0..8, 0..2] following quadratic probing.
Make use of the hash function H(X) = X mod 9. What are your observations?
Solution:
Figure P13.4. The hash table following quadratic probing and using the hash
function h(X) = X mod 9, for the keys listed in illustrative problem 13.4
Note how during the insertion of keys 13 and 22, their home buckets, which is 4 is
full. To handle this collision, quadratic probing begins searching buckets 4+1 mod 9,
Other documents randomly have
different content
church; yet when they became Christians, and of their own
accord underwent the laws of the gospel, presently as sheep to
a shepherd, and as members to the head, they became subject
to the prelate of the ecclesiastical hierarchy. Which, whether it
be true or not, is to be considered by that light which we have
from the Holy Scripture, concerning the power of our Saviour
and his apostles, over such as they had converted. But our
Saviour, as he imitated the commonwealth of the Jews in his
magistrates, the twelve and the seventy; so did he also in the
censure of the church, which was excommunication; but
amongst the Jews, the church did put the excommunicated
persons from the congregation, which they might do by their
power temporal; but our Saviour and his apostles, who took
upon them no such power, could not forbid the excommunicated
person to enter into any place and congregation, into which he
was permitted to enter, by the prince, or sovereign of the place.
For that had been to deprive the sovereign of his authority. And
therefore the excommunication of a person subject to an earthly
power, was but a declaration of the church, which did
excommunicate, that the person so excommunicated was to be
reputed still as an infidel, but not to be driven by their authority,
out of any company, he might otherwise lawfully come into. And
this is it our Saviour saith (Matth. xviii. 17): If he refuse to hear
the church, let him be unto thee as an heathen man and a
publican. So that the whole effect of excommunicating a
Christian prince, is no more than he or they that so
excommunicate him depart and banish themselves out of his
dominion. Nor can they thereupon discharge any of his subjects
of their obedience to him; for that were to deprive him of his
dominion; which they may not do, for being out of the church. It
is confessed by them that make this objection, and proved in the
former section, that our Saviour gave no authority to his apostles
to be judges over them. And therefore in no case can the
sovereign power of a commonwealth be subject to any authority
ecclesiastical, besides that of Christ himself. And though he be
informed concerning the kingdom of heaven, and subject himself
thereto at the persuasions of persons ecclesiastical, yet is he not
thereby subject to their government and rule. For if it were by
their authority he took that yoke upon him, and not by their
persuasion, then by the same authority he might cast it off. But
this is unlawful. For if all the churches in the world should
renounce the Christian faith, yet is not this sufficient authority
for any of the members to do the same. It is manifest therefore,
that they who have sovereign power, are immediate rulers of the
church under Christ, and all other but subordinate to them. If
that were not, but kings should command one thing upon pain of
death, and priests another, upon pain of damnation, it would be
impossible that peace and religion should stand together.
That no man 11. And therefore there is no just cause for
hath any just any man to withdraw his obedience from the
pretence of sovereign state, upon pretence that Christ hath
religion
against ordained any state ecclesiastical above it. And
obedience to though kings take not upon them the ministerial
commonweal priesthood, yet are they not so merely laic, as
th. God not to have sacerdotal jurisdiction. To conclude
speaketh to this chapter, since God speaketh not in these
man by his
vicegerents. days to any man by his private interpretation of
the Scriptures, nor by the interpretation of any
power above, or not depending on the sovereign power of every
commonwealth, it remaineth, that he speaketh by his vice-gods,
or lieutenants here on earth, that is to say, by sovereign kings,
or such as have sovereign authority as well as they.
CHAPTER VIII.
CHAPTER IX.
The law over 1. Having hitherto set forth how a body politic
sovereigns is made, and how it may be destroyed, this
salus populi.
place requireth to say something concerning the
preservation of the same, not purposing to enter into the
particulars of the art of government, but to sum up the general
heads, wherein such art is to be employed, and in which
consisteth the duty of him or them that have the sovereign
power. For the duty of a sovereign consisteth in the good
government of the people. And although the acts of sovereign
power be no injuries to the subjects who have consented to the
same by their implicit wills, yet when they tend to the hurt of the
people in general, they be breaches of the law of nature, and of
the divine law; and consequently, the contrary acts are the
duties of sovereigns, and required at their hands to the utmost
of their endeavour, by God Almighty, under the pain of eternal
death. And as the art and duty of sovereigns consist in the same
acts, so also doth their profit. For the end of art, is profit; and
governing to the profit of the subjects, is governing to the profit
of the sovereign, as hath been showed Part II. chapter V. section
1. And these three: 1. The law over them that have sovereign
power: 2. Their duty: 3. Their profit: are one and the same thing
contained in this sentence, Salus populi suprema lex. By which
must be understood, not the mere preservation of their lives, but
generally their benefit and good. So that this is the general law
for sovereigns, That they procure, to the uttermost of their
endeavour, the good of the people.
That 2. And forasmuch as eternal is better than
sovereigns temporal good, it is evident, that they who are
ought to in sovereign authority, are by the law of nature
establish the
religion they obliged to further the establishing of all such
hold for best. doctrines and rule, and the commanding of all
such actions, as in their conscience they believe
to be the true way thereunto. For unless they do so, it cannot be
said truly, that they have done the uttermost of their endeavour.
That to forbid 3. For the temporal good of the people, it
unnatural consisteth in four points: 1. Multitude: 2.
copulation, Commodity of living: 3. Peace amongst
promiscuous
use of themselves: 4. Defence against foreign power.
women, &c. Concerning multitude, it is the duty of them that
are in sovereign authority, to increase the
is the law of people, in as much as they are governors of
nature. mankind under God Almighty, who having
created but one man, and one woman, declared, that it was his
will they should be multiplied and increased afterwards. And
seeing this is to be done by ordinances concerning copulation,
they are by the law of nature bound to make such ordinances
concerning the same, as may tend to the increase of mankind.
And hence it cometh, that in them who have sovereign authority,
not to forbid such copulations as are against the use of nature;
not to forbid the promiscuous use of women, not to forbid one
woman to have many husbands, not to forbid marriages within
certain degrees of kindred and affinity, are against the law of
nature. For though it be not evident, that a private man living
under the law of natural reason only, doth break the same, by
doing any of the things aforesaid; yet it is manifestly apparent,
that being so prejudicial as they are to the improvement of
mankind, that not to forbid the same, is against the law of
natural reason in him, that hath taken into his hands any portion
of mankind to improve.
That to leave 4. The commodity of living consisteth in
man as much liberty and wealth. By liberty, I mean, that there
liberty as be no prohibition without necessity of any thing
may be, &c. is
the duty of a to any man, which was lawful to him in the law
sovereign by of nature; that is to say, that there be no
the law of restraint of natural liberty, but what is necessary
nature. for the good of the commonwealth, and that
well-meaning men may not fall into the danger of laws, as into
snares, before they be aware. It appertaineth also to this liberty,
that a man may have commodious passage from place to place,
and not be imprisoned or confined with the difficulty of ways,
and want of means for transportation of things necessary. And
for the wealth of people, it consisteth in three things, the well
ordering of trade, procuring of labour, and forbidding the
superfluous consuming of food and apparel. All those therefore
that are in sovereign authority, and have taken upon them the
government of people, are bound by the law of nature to make
ordinances consisting in the points afore named, as being
contrary to the law of nature, unnecessarily, either for one’s own
fancy, to enthral, or tie men so, as they cannot move without
danger; or to suffer them whose maintenance is our benefit, to
want anything necessary for them, by our negligence.
Meum and 5. For maintaining of peace at home, there be
tuum, to be so many things necessarily to be considered,
set out to the and taken order in, as there be several causes
subjects,
distinct from concurring to sedition. And first, it is necessary
one another, to set out to every subject, his propriety, and
&c. a duty of distinct lands and goods, upon which he may
sovereigns by exercise and have the benefit of his own
the law of industry, and without which men would fall out
nature.
amongst themselves, as did the herdsmen of
Abraham and Lot, every man encroaching and usurping as much
of the common benefit as he can, which tendeth to quarrel and
sedition. Secondly, to divide the burthens and charges of the
commonwealth proportionably. Now there is a proportionably to
every man’s ability, and there is a proportionably to his benefit
by commonwealth: and this latter is it, which is according to the
law of nature. For the burdens of the commonwealth being the
price that we pay for the benefit thereof, they ought to be
measured thereby. And there is no reason, when two men
equally enjoying, by the benefit of the commonwealth, their
peace and liberty, to use their industry to get their livings,
whereof one spareth, and layeth up somewhat, the other
spendeth all he gets, why they should not equally contribute to
the common charge. That seemeth therefore to be the most
equal way of dividing the burden of public charge, when every
man shall contribute according to what he spendeth, and not
according to what he gets. And this is then done, when men pay
the commonwealth’s part in the payments they make for their
own provision. And this seemeth not only most equal, but also
least sensible, and least to trouble the mind of them that pay it.
For there is nothing so aggravateth the grief of parting with
money to the public, as to think they are over-rated, and that
their neighbours whom they envy, do thereupon insult over
them, and this disposeth them to resistance, and, after that such
resistance hath produced a mischief, to rebellion.
An 6. Another thing necessary for the maintaining
extraordinary of peace, is the due execution of justice, which
power for consisteth principally in the right performance of
judging the
abuses of their duties, which are the magistrates, ordained
magistrates, for the same by and under the authority of the
necessary, sovereign power, which being private men in
&c. respect of the sovereign, and consequently such
as may have private ends, whereby they may be corrupted with
gifts, or intercession of friends, ought to be kept in awe by an
higher power, lest people, grieved by their injustice, should take
upon them to make their own revenges, to the disturbance of
the common peace; which can by no way be avoided in the
principal and immediate magistrates, without the judicature of
the sovereign himself, or some extraordinary power delegated by
him. It is therefore necessary, that there be a power
extraordinary, as there shall be occasion from time to time, for
the syndication of judges and other magistrates, that shall abuse
their authority, to the wrong and discontent of the people; and a
free and open way for the presenting of grievances to him or
them that have the sovereign authority.
The 7. Besides these considerations, by which are
suppressing prevented the discontents that arise from
of popularity, oppression, there ought to be some means for
&c.
necessary, the keeping under of those, that are disposed to
&c. rebellion by ambition; which consist principally
in the constancy of him that hath the sovereign
power, who ought therefore constantly to grace and encourage
such, as being able to serve the commonwealth, do nevertheless
contain themselves within the bounds of modesty, without
repining at the authority of such as are employed, and without
aggravating the errors, which, as men, they may commit,
especially when they suffer not in their own particular; and
constantly to show displeasure, and dislike of the contrary. And
not only so, but also to ordain severe punishments for such, as
shall by reprehension of public actions, affect popularity and
applause amongst the multitude, by which they may be enabled
to have a faction in the commonwealth at their devotion.
The 8. Another thing necessary, is the rooting out
instruction of of the consciences of men, all those opinions
youth, &c. which seem to justify and give pretence of right
necessary,
&c. to rebellious actions; such as are the opinions,
that a man can do nothing lawfully against his
private conscience; that they who have the sovereignty, are
subject to the civil laws; that there is any authority of subjects,
whose negative may hinder the affirmative of the sovereign
power; that any subject hath a propriety distinct from the
dominion of the commonwealth; that there is a body of the
people without him or them that have the sovereign power; and
that any lawful sovereign may be resisted under the name of a
tyrant; which opinions are they, which, Part II. chap. VIII. sect. 5-
10, have been declared to dispose men to rebellion. And
because opinions which are gotten by education, and in length
of time, are made habitual, cannot be taken away by force, and
upon the sudden; they must therefore be taken away also by
time and education. And seeing the said opinions have
proceeded from private and public teaching, and those teachers
have received them from grounds and principles, which they
have learned in the Universities, from the doctrine of Aristotle,
and others, who have delivered nothing concerning morality and
policy demonstratively; but being passionately addicted to
popular government, have insinuated their opinions by eloquent
sophistry. There is no doubt, if the true doctrine concerning the
law of nature, and the properties of a body politic, and the
nature of law in general, were perspicuously set down and
taught in the Universities, but that young men, who come thither
void of prejudice, and whose minds are as white paper, capable
of any instruction, would more easily receive the same, and
afterward teach it to the people, both in books and otherwise,
than now they do the contrary.
Avoiding of 9. The last thing contained in that supreme
unnecessary law, salus populi, is their defence; and
war, a consisteth partly in the obedience and unity of
necessary the subjects, of which hath been already
duty of the
sovereign,
spoken, and in which consisteth the means of
&c. levying soldiers, and of having money, arms,
ships, and fortified places in readiness for
defence; and partly, in the avoiding of unnecessary wars. For
such commonwealths, or such monarchs, as affect war for itself,
that is to say, out of ambition, or of vain-glory, or that make
account to revenge every little injury, or disgrace done by their
neighbours, if they ruin not themselves, their fortune must be
better than they have reason to expect.
CHAPTER X.
A TREATISE,
WHEREIN ALL CONTROVERSY CONCERNING
IN ANSWER TO A TREATISE
WRITTEN BY THE BISHOP OF LONDONDERRY,
ON THE SAME SUBJECT.
TO THE
SOBER AND DISCREET READER.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com