Hashing
Hashing
inserted
12.6.1 Hash table
where
identifiersare into the hash
following example,
Now, let us take the
table. identifiers.
for storing various
ht
12.9: Construct a hashtable assume aall
Example
store
identifiers in a
hash table. Let us
range 0to 25.
Since, identiarefiers26
there
Solution: We need to having the
starts with only letters from 'A'to'Z sizeis m= 26. Assume
ht whose
jdentifiers to be
fish and ape. To
letters, let us have a hash table bat, eagle, insert an
table ht are: ant, dog, cat,function. Let us define hash
function as:
inserted into hash
hash table, we require hash
identifierinto the 25 for 'a' to 'z'
65 I/rangeis 0 to
h(x) =toupper(x[0) -
us complete hash value for each of the
A. Now, let
where 65 is the ASCII value of
identifier using the above hash function: = 65 - 65 = 0. So, Insert "ant into htlol
"ant" ='A'-65
Hash value of identifier "dog"=D'-65 =68- 65 =3. So, insert "dog into ht(31
Hash value of identifier C'-65 =67- 65 =2. So, insert "cat" into ht[21
Hash value of identifier "cat" =B'-65 = 66- 65 = 1. So, insert "bat" into ht/11
Hash value of identifier"bat"= = 69 65 = 4. So, insert "eagle" into
htl4]
identifier "eagle"= E'-65
Hash value of =70- 65 =5.So, insert "eagle" into h/5)
Hash value of identifier "ish" ='F'-65
identifier "ape"= A'-65 = 65-65 = 0. So, insert "ape" into htf0)
" Hash value of
below:
Now, the hash table for first six identifiers is shown
ht[25]
ht[0] ht1] ht[2] ht(3] ht[4] ht[5] htó]
ant bat cat dog eagle fish
ht[0]
" The seventh identifier "ape" whose hash value is 0 cannot be inserted into
because, an identifier isalready placed in ht[0]. This condition is called overflow
or collision. How to avoid ">verflow" is discussed in the section 12.6.3.1.
" When there is no overflow, the time required to insert, delete or search depends
only on the time requiredto compute the hash function and the time to search on
location in ht{i]. Hence, the insert, delete and search times are independent of n
which is the number of items
E Data Structures using C - 12.15
functions
12.6.2HHash
hashfunction should satisfy two criteria:
good
A hash function should generate the hash addresses such that all the keys are
distributedas evenly as possible among the various cells of the hash table.
Computation of a key by hash function should be simple.
Now, let
us see "What are various types of hash functions?"" The popular hash
functionsare:
method, we choose a number m which is prime value and it is larger than the
In this
given elements nin array a. Here, the key item k is divided by somne
number of value. Formally, it is written as:
number m and the remainder is used as the hash
h(k) = k % m
modulo m values, the integers we get from the above function
Because, we aretaking 12.8 to know the details of how to create
m - 1. Refer example
are in the range: 0to
how an item can be accessed.
hash table and using the hash value,
12.6.2.2 Mid-square method
by
the key k is squared. A number in the middle of k' is selected
In this method, function is defined as shown below:
removing the digits from both ends. The hash
h(k) =!
removing digits from both ends of k. By selecting the middle
where l is obtained by keys are expected to give different hash values.
portion of squared number, different
of the hash table using this technique will be power of 2.
Normally, the size
example, consider key k= 2345. Its square i.e., k' = 574525
For
beginning and 25 from the end in k².
h(2345) = 45 by discarding 57in the
12.16 Sortingand searching
12.6.2.3 Folding method
In this k3,...kn
method, the key kis divided into number of parts kl, k2, of
length except the last part. Then all parts are added together as shown below: same
1272ldezi he hashfunetivn
Le e inHa)=& o mwher is HASH_ SIZE. The equivalent code
12.73 Find the index for hash table given hash value
Now. let s iolay nier of each item As vou know, it is ver easy. This can be done
ustng the tollowing ode:
for (i = 0: i<HASH SIZE; i-)
printfd. i): HO 12 3 4
Now. the above code can also be wTiten usng operator as shown below:
Data Structures using C- 12.19
for (i =0; i< HASH SIZE; itt)
values of pos:
Now, let us see the output for various
be: 0 1 23 4
¢ If pos =0, the output will 340
Ifpos= 1,the output will be: 1 2
be: 2 3 4 0 !
¢ Ifpos =2, the output will
wil! be: 3 4 0 1 2
" If pos =3, the output
willbe: 4 0 1 23
" If pos =4, the output
= (pos +i) % HASH SIZE
given by: index
So, index to hash table frorn pos is
SIZE
h_value is given by:index = (h value t i) % HASH
So, index to hash table from
table using linear probing
12.7.4 Insert an item into hash
only in the empty position. Now, let us see
the hash table This is
We can insert an item into in the hash table uSing the hash value? "
position can be
"How to find the empty item in the hash table. Each item in the hash table
achieved by accessing each
accessed using the following code:
When control comes out of the loop, "if afindex} is 0" then we can insert the item.
Otherwise, it means that "Hash table is full'". The corresponding code can be written
as shown below:
present in
each item, we check whether key to be searched is unsuccessful
accessing get
After
If found, search is successful. If aindex] is zero, we
afindex]. above code can be modified as shown below:
search. Now,the
h value H(key);
i++)
for (i = 0; i< HASH SIZE;
SIZE;
index = (h value + i)% HASH
I/Search successful
if (key a[index])return 1; key
found. So,
return 0: I/empty slot
if (a[index]= 0) I/not found
17534
12.22 DSorting and searching
int search hash table (int key, int al)
int i, index, hvalue,
h value = H(key):
for (i = 0:; i< HASH SIZE; itt)
Now, the complete program to create a hash table, insert an item into the table and to
search for a key in the hash table can be writen as shown below:
Example 12.14: Cprogram to create hash table and to search for key
#include <stdio.h>
#include <stdlib.h>
#define HASH SIZE 5
* Insert: Example 12.10: Create initial hash table */
/* Insert: Example 12.11: Compute hash value using the function: H(k)=k% m */
/*Insert: Example 12.12: Insert an item into the empty slot using linear
probing */
* Insert: Example 12.13: Search for an item in the hash table */
/* Insert: Example 2.4: Display the hash table */
void main()
int a[10], item, key, choice, flag;
initialize hash table(a); li Create initial hash table
2 Data Structures using C- 12.23
for (; :)
printf(1: Insert 2: Search\n"):
printf("3: Display 4: Exitin'"):
printf(*Enter the choice : ):
scanf(%d, &choice):
switch (choice)
scanf(%d", &item);
case l:printf(Enter the item : ;
insert hash table(item, a);
break;
printf("Enter key item: ); scanf(od", &key);
case 2:
flag search hash table (key, a);
if (flag 0)
printf("Key not foundn");
else
printf(Key foundn");
break;
of hash table\n");
case 3: printf("Contents
display _array(a, n);
printf("n");
break;
default: exit(0);
The next word to be selected is "you" whose hash value is ! andis already full. So, it
isinserted in the next available location 2as shownbelow:
0 1 2 4 5 6 7 8 9 10 11 12 13 14 15
a you tree like
ht
The word "first" with hash value 12 is inserted into ht[12] a shown below:
2 3 4 6 7 10 12 13 14 15
a you tree like first
ht
The next word find" with hash value 3 should be inserted at ht[31. But, a
word is
already present. So, insert "ind" at next free slot i.e., 4 as shown below:
2 3 4 7 10 12 14 I5
a you tree find like
first
ht
2 Data Structures using C - 12.25
word "a" with hash value l is
Ihe next already in ht(1]. So. select the next word
"place"with hash value 7. It is alreadv occupied and hence insert at next empty space
S8sshowIbelow:
10 12 13 |4
tree find like place first
ht
"to" with hash value 5 is inserted at position 5as shown below:
The word 15
6 10 12 13
01 2 3
find to like place first
tree
ht
available
and since the location is full. the next
The word "grow" has the hash value 3
show below:
Incation is 6 and so itis inserted at position 6 as 12 13 14 15
7 10 11
2 3 4 6
first
find to grow like place
a you tree
ht "and is
value 4. It is full, next free slot is 9 and hence
hash
The word "and has the below:
shown
inserted at location 9 as 13 14 15
10 11 12
0 1 2 3
4
grow like place
find to
tree
a you
ht
12.26 Sorting and searching
Solution: A hash tabieof size 5 indicates that it is required to construct a hash table
by using an array of 5 linked lists. The empty hash table can be written as shown
beiow:
The code:
for (i =0; i< HASH SIZE; it+) a<i] NULL;
Construction of Hash table: Now, let us see how to construct a hash table. Since the
size of the hash table is 5, we will have an array of 5 rows with each row having a
linked list. Obtain the words one by one, find the hash address and insert at the end of
the list in the appropriate location in the array. The hash table obtained by computing
the hash values is shown below:
>TO
1
A >YOU BRANCHOUT
2 LIKE >FIRST +>PLACE >THEN \0
3
TREE FIND +> GROW \0
4
|AND
int h value;
hvalue =H(item):
following function:
We can search for a kevusing the
Similarly.
linked lists)
EXample 12.18: search for a kev in hash table (represented as array of
temp = ali);
while (temp->link != NULL)
printf(%d -->", temp->info);
temp =temp->link:
printf("%dn",temp->info):
struct node
int info;
struct node *link;
*NODE;
typedef struct node availability list */
node from the
Example 8.2: To get a
/* Insert: end ofthelist */
at the rear
8.6: Toinsert an item
Insert: Example $/
Search for akey item in the list */
Insert: Example
8.13:
using the function: H(k) =k % m
value
Example 12.11: Compute hash of linkedlists)*/
I Insert: hash table (as arráy
Example 12.17: Insert item into
Insert:
12.30 D Sorting and searching the hash
table (adjacency list
itemin
Searchfor an
/* Insert: Example 12.18:
hashtable */
*Insert: Example 12.19: Display the
void main()
NODE af 10}:
flag,i;
item, key, choice,
int
/ Create initial hash table
itt) alil = NULL;
for (i = 0: i < HASH SIZE;
for (: :)
big = a[pos];
i= log10(big): number */
pow(10,i); /* The position of largest
return
12.32 D Sorting and
searching
After findinitem
g into the appropriate location. For example, if item is 45
the hash value, divide cach item to be sorted using this hash
insert the
is 10, valuc
45/10 is 4. So, insert 45 into the 4 location. If some items are and hash valandue
in this
in order.location, already
insert it in the appropriate position such that items in that presenm
inserted in this way, obtain the items present in cach list in the array onethelocatiteims
on are
For this reason, we use an array of ordered linked list. Once all are
display. The Cfunction to sort the items Using Address Calculation by one and
shown below: Sort(Hash
Sort) is
EXample 12.22: C function for Address Calculation Sort (Hash
Sort)
void hash sort(int al], int n)
NODE b[10], temp;
int i, j. digit, h value;
h value = hash(a,n);
for (i=0; i< 10; itt) b[i] =
NULL; /* Empty hash table */
for (i =0; i<n; it+)
[* Insert orderly into hash
table */
digit =a[i] /h_ value;
b[digit] =insert(a[i],b[digit));
#include<stdio.h>
#include <stdlib.h
#include <math.h
structnode
int
info;
struct node *link;
NODE:
typedef struct node*
read array elements */
%Include Example 2.3: CFunction
Include Example 2.4: C Function display array elements */ availability list */
/8 Function to get a new node from the
Include Example 8.2: C */
/*
Example 8.17: function
C to create an ordered linked list
/* Include function to find the hash value *
J* Include Example 12.21: Cfunction for Address Calculation Sort (Hash Sort) */
12.22:C
/* Include Example
void main()
int n, a[40];
printf("Enter the value of nn");
scanf("%d",&n);
hash sort(a,n);
printf("The sorted vector is\n");
display_array(a, n);
12.34 D Sorting and
searching
12.10 Search for enmployee details using hashing
Now, let us create ahash table for storing records of employce details
and name of the
cmployee and search for an employee id. The structureconsisting of id
can be written as shown
below:
#define HASH SIZE 5
d eclaraion
typedef struct employee
int id;
char name(20]:
EMPLOYEE:
Ihe program designed in the section 12.7 (see section 12.7 for
detailed desig) is
Siightly modified to incorporate structures. The complete program is
shown below:
Example 12.24: Create a hash table for employee record and search using id
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HASH SIZE 5
typedef struct employee
int id;
char
name[20];
}EMPLOYEE:
/* Create initial hash table */
void initialize hash
table(EMPLOYEE al])
int 1:
a[i].id = 0;
Data Structures using C- 12.35
Computehash value using the function: H(k) - k % m */
intH(intk)
hash table */
/* Search for employee id in theEMPLOYEE a[])
int search hash table (int key,
int index, h value;
h value = H(key);
for (i =0; i< HASH SIZE; itt)
index = (h value +i) % HASH SIZE;
/ Search succèssful
a[index].id) return 1;
if ( key
lempty slot found. So, key
if (a•index].id ==0) return 0; |/ not found
return 0; 1/Unsuccessful
if (i == HASH SIZE)
12.36 Sorting and searching
* Display the hash table */
void display hash table(EMPLOYEE a], intn)
int i;
for (i = 0; ii<n; itt)
void main()
EMPLOYEE a[10];
char
name(20];
int
key, id, choice, flag;
initialize hash table(a); | Create initial hash table
for (;:)
printf("1: Insert 2: Searchln");
printf("3: Display 4:Exitn");
printf("Enter the choice : ");
scanf("%d", &choice);
switch (choice)
case 1:printf("Enter emp id :"); scanf("%d", &id);
printf("Enter the
name:"); scanf("%s", name);
insert hash table(id, name, a);
break;
case 2: printf("Enter key key : ");
flag = search hash table
scanf("%d", &key);
(key, a);
if (flag 0)
else printf("Key not foundn");
printf("Key foundn");
break;