












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!













Introduction For the past several weeks we have studied a variety of advanced data structures whose primary purpose was the representation of data contained in main memory that supported an algorithm during its execution. With the exception of B-trees, in which part of the data was resident in main memory and part was resident in secondary memory, all of these data structures were designed for data representation in main memory. Hashing is a variant of a more general file organization technique called a direct file. A direct file is a variant of an even more general type of file organization known as an indexed file. Indexed files typically consist of two main structures, an index structure and a main structure. Similar to the concept employed in B*-trees and B+-trees with their index set and sequential set. There are many different variations of indexed files, however, they can be broadly categorized into two categories which are based primarily on the density of entries in the index structure compared to the number of entries in the main file. These two primary categories are sparse index files and dense index files. A hash file or direct file falls generally under the category of a dense index file, although it is a very special variant of the dense index file. Hash files themselves are typically categorized in two different manners. The first depends on whether the file structure is resident in main memory or on secondary memory. The former is called internal hashing while the latter is called external hashing. You may have been introduced to internal hashing in CS2 or perhaps in System Software (COP 3402) as the commonly referred to “hash table” or “hash file” is a common data structure used within a compiler or assembler as a method for implementing a symbol table. External hashing is a common database approach for hashing secondary memory (primarily disk-based files). The primary difference between internal hashing and external hashing is that in external hashing the hashing function is tailored to take advantage of the block- based access methods on the disk drive. This allows a single hash function value to “load” into main memory an enormous amount of data in one single disk “fetch” operation, whereas with internal hashing typically either a single value (record) or very small number of values are returned for a single hash value. In this set of notes we’ll give a quick review of common hashing techniques and take a quick look at internal hashing and the problems associated with internal hashing. We’ll examine external hashing and finally we’ll look at hashing
techniques that allow for dynamic file expansion, something which is not feasible (in terms of time) with internal hashing. Hash Functions Hash functions are a specific case of a more general technique known as key- to-address transformations (KTA transformations). There are many different KTA transformation techniques possible. Figure 1, illustrates the hierarchy of KTA transformations. Figure 1 – Key-to-address transformation hierarchy. Distribution dependent transformations depend on at least approximate knowledge of the key values that will be expected. The benefits that can be gained by distribution dependent techniques depend on open-addressing, bucket size. file density, and the appropriateness of the transformation itself. For small bucket size and a good distribution algorithm, the improvement over randomizing transformations can be significant. On the other hand, the liabilities of distribution dependent transformations are major, since a change in the key distribution can cause these methods to generate many more collisions than a randomization would generate for the same data. A benefit of some Key-to-address Transformations Known Key Distribution Unknown Key Distribution Deterministic Transformations Probabilistic Transformations Sequence Maintaining Transformation Hashing Techniques Exponential Transform Piecewise Linear Transform Digit Analysis Remainder of Division XOR Folding and Adding
number then the sample of records that would be examined will probably show a uniform distribution over the low-order three digits. A tabulation simply lists the frequency of distribution of zeros, ones, twos, and so on. The digit positions that show a reasonably uniform, even distribution are candidates for use as digits in the file address. A sufficient number of such digit positions must be found to make up the full address; otherwise combinations of other digit positions (perhaps taken modulo 10 or as appropriate) can be tested. A sequence maintaining transformation function can be obtained by taking a simplified inverse of the distribution of keys found. The addresses are generated to maintain sequentiality with respect to the source key. In a piece- wise linear transformation the observed distribution is approximated either automatically or manually, by simple line segments. This approximation is then used to distribute the addresses in a complementary manner. The remainder of division (modulo operation) of the key by a divisor equal to the number of record spaces allocated in the file, can be used to obtain the desired address. Division is in some sense similar to taking the low-order digits, but when the divisor is not a multiple of the base of the number system of the key (or the hardware), information from the high-order portions of the key will be included; and this additional will have a positive effect on the number of addresses generated and thus on the uniformity of the generated addresses. Large prime numbers are generally used as divisors, since their quotients exhibit a well-distributed behavior, even when parts of the keys do not. In general, divisors that do not contain small primes (<= 19) are adequate. Empirical data has shown that division tends to preserve better than other methods preexisting uniform distributions, especially uniformity due to sequences of low-order digits in assigned identification numbers. The remainder does not preserve sequentiality. The problem with division is in the capability of the available division operation itself. Frequently the key field to be transformed is larger than the largest dividend the divide operation can accepts, and some hardware does not have division instructions which provide a remainder (although this is rare). When this occurs, the remainder (address) can be calculated according to the expression: m m key address key The floor operation is necessary to prevent a smart optimizer from generating address = 0 for every key, which would lead to an extreme number of collisions (n-1 if n records are to be stored). The exclusive-or technique typically divides the key digit string is segmented into parts which match the required address size. Using this operation results in
random patterns for random binary inputs. The various segments are then exclusively-or’ed together to produce the address. Segment sizes need to be chosen carefully so that they have no common divisor relative to word sizes. This is among the faster KTA transformations available and is widely used. Folding and adding of the key digit string produces a shorter string as the address and is a commonly used hashing technique. Alternate segments of the key digit string are bit-reversed. Internal Hashing The primary design criterion for an internal hash file is to achieve as nearly as possible O(1) access time to any element in the file based upon access through the hash field (the component of the file element on which the elements are hashed). Although the hash field may be any component of an element in the file, it is typically the key value (component) on which the hashing occurs. In order to achieve this O(1) access criterion we need to first determine how a hash function operates. Although the hash field does not need to be a key of the file, in most cases it is and it is then typically referred to as the hash key. For internal files (those which have no component in secondary memory), hashing is typically implemented as a hash table through the use of an array of records. The typical configuration is shown in Figure 2. Figure 2 – Typical Internal Hashing Configuration. Collision Resolution in Internal Hashing key value (in) address (out) main file (M records) KTA Transform Function
1 Bob 2 Betty (^3) Carl 4 … 25 Details: Retrievals are handled by hashing the key and comparing the data at the location provided by the hash function. If the two values are not equal the location is incremented and the comparison is made again against the value in this new location. This is repeated until either the key value is found or an empty location is encountered. Deletion must be lazy. This entails marking the item as deleted but leaving it in place in the table (using a delete bit) without actually physically removing it from the table. This ensures that the look-up operation always works. Items which have been lazily deleted are only removed when they won’t break a chain valid items or when a new item can be inserted at this location which overwrites the deleted item. Analysis: Assuming that the probes are independent, the average number of locations (cells in the table) that will be examined in a single probe is: 1/(1-). This comes simply from the fact that the probability that a location is empty is 1-. The above assumption is bad! In fact, linear probing causes a phenomenon called primary clustering. These clusters are blocks of occupied cells (locations). These blocks cause excessive attempts to resolve collisions. Taking this into account, the average number of cells that will need to be examined for an insertion into the hash table is: Hashing - 7 Definition Load factor: The load factor of a probing hash table is the fraction of the table that is full. The load factor is represented by the symbol , and generally, ranges from 0 (empty table) to 1 (full table).
2 1 1 1 (^2) ^
For half-full tables, i.e., when 0.5, this is an acceptable value of 2.5, but when = 0.9, the search will require that 50 cells (on the average) be examined! We need a solution that eliminates primary clustering. The following picture illustrates (sort of!) the long-term effect primary clustering has on the file density. Quadratic Probing Quadratic probing eliminates the problem of primary clustering caused by linear probing. The technique is similar to linear probing but the location increment is not 1. Specifically, if the hash function produces a hash value (a location or cell index) of H and the search at location H is unsuccessful, then the next location that is searched is H+ 2 , followed by H+ 2 , H+ 2 , H+ 2 , …, H+i 2 (using wraparound as before). Example: Suppose our hashing function is a simple mod operation on the size of the hash table. If the hash table is size 10 and the input sequence is: Insert(89), Insert (18), Insert (49), Insert (58), Insert (9). Then the hash table is filled as shown below: The shaded areas indicate areas of the file that are occupied with records. The unshaded areas are unoccupied areas containing no information. Primary clustering tends to divide the file space into discrete clusters which further increases the probability of collision and tends only to expand each cluster rather than spread the information across the file space.
+ 2(1) – 1]mod 10 = [8+1]mod 10 = 9. This too results in a collision so another value of H must be calculated as follows: H 2 = [H 1 + 2(2) – 1]mod 10 = [9+3]mod 10 = 2 which is empty, so insertion occurs at position 2 in the hash table. Using the shift operation this example proceeds as (with numbers shown in binary form): Initially H 0 = 58 mod 10 = 8 and collision results. Then i = 0001 and H 0 = 1000. H 1 = [1000 + 0010 – 0001]mod 10 = [8+1]mod 10 = 9. This too results in a collision so another value of H must be calculated as follows: H 2 = [1001 + 0100
- 0001]mod 10 = [9+3]mod 10 = 2 which is empty, so insertion occurs at position 2 in the hash table. Quadratic probing eliminates primary clustering but introduces the problem of secondary clustering. Elements which hash to the same location will probe the same set of alternative locations. This however, is not a real concern. Simulations have shown that, in general, less than 0.5 additional probes are required per search, and this only occurs for high load factors. If secondary clustering does present a problem for a given application, there are techniques which will eliminate it altogether. One of the more popular techniques is called double hashing in which a second hash function is used to drive the collision resolution. Chaining Maintain an array of linked lists at each hash addressable location. The hash function returns an index of a specific list. Insertions, deletions, and searches occur in that list. If the lists are kept short, then the potential performance bottleneck is eliminated. λ is calculated by dividing the total number of nodes N, by the number of lists which are maintained M. λ= N/M λ is no longer bounded by 1.0 but has an average value of 1.0. The expected number of probes for insertion and an unsuccessful search is: λ. The expected number of probes for a successful search is: 1 + λ/2. Example M = 6, N = 15, = N/M = 15/6 = 2.
Hash Address List 0 1 2 3 4 5 Each list referenced by the “hash table” is a singly-linked list (see previous notes for implementation details). The singly-linked lists shown above do not have a tail node. Would the use of a tail node be beneficial in this data structure? The answer is yes, it could help in two different ways! Notice that there is no implied order to the elements of a specific list. This is done since insertion into a hash table should be an O(1) operation. If the list is maintained in alphabetical order – then insertion will not be an O(1) operation and we would violate one of the specifications of the hash table data structure. This also happens in the implementation shown above since we have no way, other than traversing the list, of finding the end of the list. Therefore a “better” implementation is the one shown on the next page. Hash Address List Al Ann Art Ali Kris Kristi Bo Cris Cindi^ Cyn Calli Carl Jimi Jane Jack
Notice that this “better” implementation still does not provide O(1) insert time, unless we can identify (have a reference to) the node immediately preceding the tail node in any given list. For example, if we want to insert Alice into the first list, having a tail node only tells us where the end of the list is, not where the node next to the end of the list is! What do we do to get our required O(1) insert? The answer has been available all along, and none of the “improvements” that we have made to our structure have done anything toward this end. Recall some of the issues we discussed when dealing with the implementation of linked lists in CS2. We stated that in a list without header and tail nodes that insertion at either end of the list was a “special case” that was different from inserting in the middle of the list. So we put header and tail nodes in to prevent the special cases from occurring. However, in our hash table structure, there has been a header node all along. It is embedded in the hash table itself as the reference to the chain for each hashable location. Therefore, to achieve O(1) insertion time, we simply perform ALL insertions at the head of the list rather than at the tail of the list. (A potential benefit of this is that the chain will contain the elements in the order of their arrival – i.e. they appear in entry order within each chain.) This again illustrates that you need to be aware of the various implementation issues for all of the data structures that are involved in any application. The final diagram illustrates the insertion of a newly hashed value into our hash table. Al Ann Art Ali Kris Kristi Bo Cris (^) Cind i Cyn Calli Carl Jimi Jane Jack TAIL
Hash Address List 0 1 2 3 4 5 Hash tables can be used to implement insert and find operations in O(1) time, on the average. There are many implementation factors that can influence the performance of the hash table such as the load factor, the hash function itself, file size, input rates and distributions, as well as many other factors. It is important to pay attention to these details if you are to perform these operations in O(1) time. External Hashing Hashing techniques for secondary storage, primarily disk files, is called external hashing. Basically, external hashing is the same as internal hashing, however, the hash address is optimized to take advantage of the block-oriented nature of external memory and is thus optimized toward the hash bucket size. In an external hashing environment a bucket is either a single block or a cluster of contiguous blocks. Which is used depends on several factors which include the size of the physical records and how this relates to the blocking factor, whether the records are spanned or un-spanned, whether the records are compressed or not as well as several other factors. The hashing function maps a key into a relative bucket address rather than to assign an absolute block address to the Al Ann Art Ali Kris Kristi Bo Cris (^) Cind i Cyn Calli Carl Jimi Jane Jack TAIL James
Although it is more of a problem with external hashing than internal hashing, a non-key based search in a hashed file is a very costly operation in terms of time. There is another file organization technique in which the records of the file appear in no particular order (analogous to an unsorted array) called a heap file. Since there is no order to this type of file on any field within the records of the file, sequential searching operations are the only suitable search technique. Hashed files, on the other hand, were designed to provide O(1) access time to the file. This access time was based upon the hash field (again, typically the key field). If access to the hashed file is to be through any field other than the hash field (this includes secondary key fields) access deteriorates to that of a sequential search! Static vs. Dynamic Hashing The hashing schemes that we have examined for internal hashing are basically the same as those used for external hashing with the only slight change being the adaptation for bucket addresses relating to physical block addresses in the case of external hashing. The hashing techniques that we have seen so far are called static hashing techniques. In static hashing a fixed number of file locations (size of the address space for internal hashing and the number of allocated buckets for external hashing) are allocated to the file structure based upon the initial requirements. This is a serious drawback for dynamic files. A dynamic file is one whose size (total number of bytes required by all records in the file) changes, perhaps drastically, over time. Suppose that we allocate a total of M buckets for the address space of a hashed file and let m be the maximum number of records that can fit into a single bucket; then at most ( m M ) records will fit into the allocated address space. If the number of records ultimately turns out to be substantially fewer than ( m M ) records, we will be left with a lot of unused space. On the other hand, if the number of records increases to substantially more than ( m M ) records, numerous collisions will result and retrieval operations will be significantly slowed due to the long lists of overflow records that will require traversing. In either case, the number of blocks allocated to the file M may need to be changed. This will require the development of a new hash function (it must handle the larger allocation) to redistribute the existing records into the new space allocation. This type of reorganization is extremely time consuming for large files. There are two primary schemes that have been developed to allow dynamic resizing of hashed files. Both schemes are designed for external hashing applications and are not, in general, applicable to internal hashing. The first type maintains an access structure, similar to an indexed file, in addition to the main file. The most common techniques which fit into this category are called dynamic hashing and extendible hashing. The second type does not maintain
the access structure but allows for dynamic resizing. The best example of this latter type is called linear hashing. These hashing schemes take advantage of the fact that the result of the hashing function is usually a nonnegative integer and therefore can be represented as a binary number. The access structure is built on the binary representation of the result of applying the hashing function to the hash field value of a record, which is a string of bits. This is called the hash value of the record. Records are distributed among buckets based on the values of the leading bits in their hash values. Dynamic Hashing In dynamic hashing the number of buckets is not fixed as in regular hashing but expands and contracts as needed. The file can start with a single bucket; once that bucket is full, an insertion will cause the bucket to overflow. The overflow will cause the bucket to split into two buckets. The records are distributed among the two buckets based on the value of the first bit of their hash values. All records whose hash value starts with a 0 bit are stored in one bucket, and all those whose hash value starts with a 1 bit are stored in the other bucket. The indexing structure is a binary tree in which convention has set the left child pointers for internal nodes correspond to a 0 bit and the right child pointers for the internal nodes correspond to a 1 bit. Leaf nodes hold pointers to buckets. Figure 4 illustrates the basic structure of a dynamically hashed file. Figure 4 – Structure of a dynamically hashed file. Figure 5 illustrates more of the details of the dynamically hashed file structure. In Figure 5 the tree portion of the hashed file (the index structure) has leaf data file buckets
add a new level to the index structure, by replacing the current leaf node associated with the “100” bucket with a new internal node and pointers to two leaf nodes, one for key values “1000” and one for key values “1001”. Notice that adding a level to the index structure requires that we differentiate keys on one more bit along this path. The remainder of the index structure is unchanged. Figure 6 illustrates this splitting and redistribution of the key values in the current “100” bucket into the “1000” and “1001” buckets. Figure 6 – Bucket splitting on overflow in a dynamically hashed file. Key value “100110” inserted is inserted into the file structure shown in Figure 5. As illustrated by the insertion example shown using Figures 5 and 6, the dynamically hashed file can easily expand when required by allocating another bucket and redistributing the key values into two buckets one level deeper in the index structure. The dynamically hashed file structure can also contract when a deletion empties a bucket causing an underflow condition to occur. Using Figure 5 as the starting point, assume that both key values “001001” and “001011” are deleted from the file. Since these are the only two key values in their bucket, the bucket will empty and the two leaf nodes will contract into their parent node which will become a leaf node and a single bucket (the contract bucket’s sibling) will be the only remaining bucket in this subtree. Notice too, that no redistribution of key values will be required on a contraction. Figure 7 illustrates the changes 0 1 1 1 1 1 0 0 0 0 0 1 the buckets 000011 000110 000101 001001 001011 010000 101001 101110 110000 110101 100011 100001 100111 100100 100110
that will occur to the file shown in Figure 5 when these two key values are deleted. Figure 7 – Bucket contraction caused by an underflow on deletion. Key values “001001” and “001011” are deleted from the dynamically hashed file shown in Figure 5 which produces this file structure. If the hash function distributes the key values uniformly, the index structure will be balanced. In some systems, rather than wait for an underflow condition to develop on deletion, contraction of two siblings can occur at any point in time when the total number of key values in the two sibling buckets is less than or equal to the size of a single bucket. This make optimal use of bucket space but may unnecessary splitting on insertion. Whether to use advance contraction or not depends in part on the access patterns to the file. If insertions tend to dominate deletions, then advance contraction is not typically a good idea, on the other hand, if deletions tend to dominate insertions, then bucket space utilization can be optimized through advance contraction. 1 1 1 0 0 0 0 1 the buckets 000011 000110 000101 010000 100011 100111 100100 100001 101001 101110 110000 110101