Modue 5
Modue 5
SEQUENTIAL SEARCH
Sequential_search(key)
Input: An unsorted array a[], n is the no.of elements, key indicates the
element to be searched
Output: Target element found status
DS: Array
1. Start
2. i=0
3. flag=0
4. While i<n and flag=0
1. If a[i]=key
1. Flag=1
2. Index=i
2.end if
3. i=i+1
5. end while
6. if flag=1
1. print “the key is found at location index”
7. else
As an example let us consider a hash table of size 10 whose indices are 0,1,2,…
9.Suppose a set of key values are 10,19,35,43,62,59,31,49,77,33.Let us assume the
hash function as stated below
1) Add the two digits in the key
2) Take the digit at the unit place of the result as index , ignore the digits at tenth
place if any
Using this hash function, the mapping from key values to indices and to hash tables are
shown below.
HASH FUNCTIONS
There are various methods to define hash function
Division method
One of the fast hashing functions, and perhaps the most widely accepted, is the
division method, which is defined as follows:
Choose a number h larger than the number n of keys in K. The hash function H is
then defined by
H(k)=k(MOD h) if indices start from 0
Or
H(k)=k(MOD h)+1 if indices start from 1
2nd, 4th and 6th position are chosen as their hash values.
FOLDING METHOD
Another fair method for a hash function is folding method. In this method, the
key k is partitioned into a number of parts k 1 , k2..kn where each part has equal no.of
digits as the required address(index) width. Then these parts are added together in the
hash function.
H(k)=k1+k2+…+kn. Where the last carry, if any is ignored. There are mainly two
variations of this method.
1) fold shifting method
2) fold boundary method
Fold Shifting Method
In this method, after the partition even parts like k2, k4 are reversed before
addition.
Fold boundary method
In this method, after the partition the boundary parts are reversed before
addition
Example
-Assume size of each part is 2 then, the hash function is computed as follows
probed are i+12 ,i+22 ,i+32 ..etc . This method substantially reduces primary clustering,
but it doesn’t probe all the locations in the table.
Open Hashing
Closed hashing method for collision resolution deals with arrays as hash tables and thus
random positions can be quickly refer red. Two main disadvantages of closed hashing
are
1) It is very difficult to handle the problem of overflow in a satisfactory manner
2) The key values are haphazardly intermixed and, on the average majority of the
key values are from their hash locations increasing the number of probes which
degrades the overall performance
To resolve these problems another hashing method called open hashing or separate
chaining is used.
The chaining method uses hash table as an array of pointers. Each pointer points a
linked list. That is here the hash table is an array of list of headers. Illustrated below is
an example with hash table of size10.