0% found this document useful (0 votes)
31 views25 pages

Hashing

Uploaded by

sueana095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views25 pages

Hashing

Uploaded by

sueana095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

12.

12 Sorting and searching


12.5 Hashing
element in
We have time required to accesS any
irespective of its position is same. The physical location of i item in the arraythe can be
already seen that the
element of the array with i and
ar ay
calculated by multiplying the size of each
the base address as shown below: adding
io
Loc(Ai) =Base(A)+ w*{i-lb)
Here, i is the index, wis the size of each element of the array and lb is the
bound. Using this formula, the address of any item at any specified position i lower
obtained and from the address obtained, we can access the item. The similar can beis
used in hashing to store and retrieve the data. So, the hashing technique is idea
independent ofn where n is number of elements. essential y
Example 12.8: Create a hash table and using hash function for 5 items:
For example, consider the eiements: 11, 12, 13, 14 and 15 and
function: consider the following
H(k) =k %5 1/Hash function is just a function
The value of each function for the items: 10,
shown below: 11, 12, 13 and 14 can be obtained as
H(k)= k %5 I| Hash function
H (10) =10%5=0
H(11) = 11%5 =1 Insert 10into table af0]
H (12) = 12 % 5 =2 Insert 11 into table a[1]
hash values Insert 12 into table a[2]
H(13)= 13 % 5 = 3
H(14) =14 %5 =4 Insert 13 into table a[3]
Insert 14 into table a[4]
Thus, the table obtained after
is shown below: inserting each of the items using hash value as
the index
a[0] 10
a[l] 11
a[2] 12 The table thus created
a(3] 13 the hash table using elements and hash
values 1S
a[4] 14
Now,leet us see
"What is
hash value? What is Data Structures using C- 12.13
pefinition: Afunction can be
hash function?"
smaller
table by used to provide a
andthe
transforming a key mapping between large original data
isinformat ion
value
index returned
transformsa data into
by this
function called into an index to the table. The
hash value to a table is hash value. The function that
called hash function.
Now,let us see What is a hash
table?"
Definition: The data can be stored in the
Lach function which gives a hash value asform of atable using arrays with the help of
an index to access any element in the
This table on which insertion, deletion and table.
helpp of hash value is called hash table. retrieve operations iakes place with the
A hash table can be
implemented as an array ht[0..m-11. The size of the nasn
table is limited and so it is necessary to map the given data into this fairly restrncted
set of integers. The hash function assigns an integer value from 0to m-1 to keys and
these values which act as index to the hash table are called hash addresses or hash
values.

Now, let us see "What is hashing?"


pefinition: This process of mapping large amounts of data into a smaller table using
hash function, hash value and hash table is called hashing.
Now, let us see "What are the different types of hashing techniques?" The two types
of hashing techniques are:
Static hashing
’ Dynamic hashing
12.6 Statichashing
Now, let us see "What is static hashing?"
amounts of data into atable whose size is
Definition: Thisprocess of mapping large
during compilation time is called static hashing. In static hashing, all the data
fixed called hash table. The hash table is implemented
items are stored in a fixed size table t
low index and m -las the high index. Each item
as an array ht{0..m-1]with 0 as theht[l J,.....t[m-- 1l] where mis the size of the table
in the table can be stored in ht[0], 5, 7, 11and so on. The items are inserted into
usually with a prime number such as
obtained from the hash function.
the table based on the hash value
searching
12.14 DSorting arnd

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:

> Division method


’ Mid square method
>Folding method
> Converting keys to integers
12.6.2.1 Division method

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

h(k) =kl +k2+ k3+ ......kn


For example, consider key k = 123987234876. The partitions are kl =12, k2 =39, k3
= 87. k4 = can be obtained
23, k5 = 48, kó 76. Now, the hash value by
the
partitioned kevs as shown below: adding all
h(k) = 12+ 39 +87 +23 +48+ 76=285
12.6.2.4 Converting keys to integers
In this method, if key k is a string, the hash value can be obtained by converting this
String into integer. This can be done by adding all ASCII values of each character in
the string. For example, let k = "ABCD". The hash value can be calculated as shown
below:
h("ABCD") ='A'+ B' +C"' +D'= 206
The equivalent function can be written as shown below:
int string io int(char k)
int i, n =0:

while (k[i != \0') I/Scan the string till the end


n t= k[i]; IlAdd the ASCII value of each character
itt;

return n; I/ hash value of string k is returned

12.6.3Overflow handling (Collision and its detection)


First, let us see *When overflow occurs?" or "What is
collision during hashing?"
Definition: If the size of the hash table is fixed and the size of the table is
than the total number of keys smaller
generated, then two or more keys will have the same
hash address (also called hash value). This
phenomenon of two or more kevs being
hashed to the same location of bash table is called collision.
Data Structures using C- 12.17
Observethefollowing points:
We can expect collision even if the number of keys is less than the size of the hash
table (See example 12.9). all keys may
Most of the time collision cannot be avoided and in the worst case
hash value. In such situation all the keys
nay be siored in only one
havethe same the wost case.
cellinthe form of alist and so, it is required to search all nkeys irn hash
But, with approprately chosen size of the hash table and using a good
assumptions, the
Gunction, this phenomenon will not occur and under reasonable
expected time to search for an element in a hash table will be (1).
where insertion, dcietion
So, in practical situation, hashing is extremely efective
and searching takes place frequently.
avoid collis:on?"
Now, let us see "How to
avoid overflow in hashing?" or "Howv to
The various hashing techniques using which collision can be avoided are:
" Open addressing
Chaining
12.7 Open addressing
the amount of space available for storing various data is
In open addressing hashing, fixed array for the hash table. So, all the keys are
fixed at compile time by declaring a tabie,
fixed hash table itself without the use of linked iists. In such a
stored in this
avoided by finding another, unoccupied location in the array. The
collision can be
collision can be avoided using linear probing.
following:
create a hash table. To create a hash table, we need the
Let us
Initial hash table
Select the hashing function
location in the hash table
" Find the index of each

12.7.1 Create initial hash table


table
How to create initial hash table?" Assume the size of the hash
Now, let us see shown below:
HASH SIZE = 5 and the hash table can be pictorially represented as
is
a[1] a[2] a[3] a[4]
a[0]
shown
storing 0values in each location as
The empty hash table is indicated by
below:
r(=HASH SIZE )}

1272ldezi he hashfunetivn
Le e inHa)=& o mwher is HASH_ SIZE. The equivalent code

Eumpie 1ll:Compur hash val sing he iNn: H(k) =k m


int H nt k)

returnk a HASH SIZE:

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)

printf("%d, i% HASH SIZE): /0 I 2 3 4

"I want to display ailindices starting from specified position


Now, the question is modifying the above code by
Hoy we can achieve?" This can be done by
say pos. bclow:
adding posto i and then perform mod operation as shown
for (i = 0; i< HASH SIZE; itt)

printf("%d", (pos + i)% HASH SIZE);

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:

h value = H(item); SIZE:; it+)


for (i= 0: i< HASH
HASH SIZE:
index = (h value+i)%
afindex}:
The
be obtained by compar1ng a;index with )in the above code.
The emptyslot can shown below:
modifiedcode can be written as
12.20 Sorting and searching
hvalue = H(item):
for (i =0; i<HASH SIZE; itt)
index = (h value +i) %HASH SIZE;
if(a[index]==0) break; Il empty slot found

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:

if (a[index] ==0) l/empty slot found


a[index]=item;
else
printf("Hash table is fulln"); 1/ No empty slot
Now, the complete function can be written as shown below:
Example 12.12: Insert an item into the empty slot using linear probing
void insert hash table (int item, int a[|)
int i,index, h value;
h value = H(item);
for (i= 0; i <HASH SIZE; it+t)
{
index =(h value + i) %HASH SIZE;
if (afindex]=0) break; ll empty slot found

if (afindex]*=0) Hempty slot found


a[index] = item; /insert item into empty slot
else
printf("Hash table is fulln"); I/No empty slot

12.7.5 Search for an item in the hash table


We can easily search for an item in the hash table. We access each item in
the hash
table using the following code:
Data Structures using C- 12.21
H(key):
hvalue = i<HASH SIZE; itt)
= 0; i
for (i
index = (h value + i)% HASH SIZE.
a[index] I/access each item

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

not control comes out of


present,Unsuccessful".
still item is Now the
elements have been compared anddisplay the message
If all
loop and key is not present and we
below:
the written as shown
above code can be
h value= H(key):
HASH SIZE; i+)
for (i = 0; i<
value+i)% HASH SIZE;
index = (h / Search successful
a[index]) return 1;
if ( key found. So, key
return 0; 1/empty slot
I/not found
if (a[index] =0)
|/Unsuccessful
retun 0:
if(i= HASH SIZE)
shown below:
function can be written as
Now, the complete
for an iten in the hash table
Exampie 12.13: Search

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)

index = (h value + i) %HASH SIZE;


I/Search successful
if( key - alindex)) return 1;
if (a[index] =-0) return 0; l empty slot found. So, key
/ not found

if (i =HASH SIZE) return 0; I/Unsuccessful

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);

(using open addressing method)


Construct ht of size 15
a hash table you, first, find, a, place, to, grow, and, then,
Example 12.15: like, a, tree,
following words:
to store the
branch and out
us find the hash address
Let
Find hash address for each word". and taking the remainder by
Solution: Now, we positions of alphabets in the word are shown below:
sum of hash values
by taking the 15.The various hash addresses or
dividing it by
12.24 D Sorting and searching
hash address sum %l5
SI. No Words Sum of positions
= 37 7
like 12+9+11+5
=|
2 1
20+18+5+5 =48
tree
4 VOu 25+15+21 =61
6+9+18+19+20 = 72 12
first
6+9+14+t4 = 33
find
1
7
16+12+1+3+5 37 7
8. place
to 20+15 = 35
10. 7+18+15+23 =63
grow
1+14+4 = 19 4
11. and
12. then 20+8+5+ 14 = 47
13. branch 2+18+1+t14+3+8 = 46
14. out 15+21+20 = 56 11
Creating hash table: The words are taken in the order of serial number from the
above table and inserted into the hash table one by one based on the hash address
(value or index). The words "ike", *g" and tree" are inserted into positions 7, 1
and 3respectively as shown below into hash tabie:
3 4 6 7 8 10 12 13 /4 15
a tree like
ht

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

3 4 5 like place and


first
2
find to grow
al you tree

ht inserted into next free location 10


has the hash value 2. It is full. It is
The word "then" 13 14 15
as shown below: 10 11 12
6 and then first
3 4 place
0 1 2 grow like
find t o
al you tree
location
into next free
ht
value 1. It is full. It is inserted
has the hash
The word "branch" 12 13 14 15
1las shown below: 9 10 11
7 then branch first
5 6 and
2 3 4 like place
0 1 find to grow
tree
a you location 13
ht full. Itis inserted into next free
has the hash value l1. Itis
The word "out" 11 12 13 14
as shown below: 8
10
6 7
and
then branch first Out

0 1 2 3
4
grow like place
find to
tree
a you
ht
12.26 Sorting and searching

12.8 Chaining method using which collisions can be


simple item has to be
valueis used toinserted,
a very linked lists. If an
The chaining technique is array
of
hash find the
avoided. This is achieved using an obtained. This
hash value is appropriate function an item can be
using a hash function, the and usingthe value.
list to which the item is to be added than one key has same hash thus all the keys
more and
inserted at the end of the list. If
be inserted at the end ofthe list collision is
hashed into same hash value will
to ba
avoided.
technique takes less time. When an item has
The searching using this using hash function. This hash value corresponds to
Searched, we find the hash value obtain the address ofthe list. If the address of the list is
an index which willbe used to present and report unsuccessful search. Jf the
NOLL, the item we search for is not
the list is not NULL, that list is traversed sequentially to search for the
address of successful search and if end of list is
item. If an item is found in the list, report
encountered report unsuccessful search.
to avojd
Example 12.16: Construct a hash table ht of size 5 (using chaining method
collision) and store the following words: like, a, tree, you, first, find, a, place, to,
grow, and, then, branch, out

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;

Design of Hashing funetion: Let us design a


accept a string consisting of a key and add the simple hashing function which wil!
compute the remainder by dividing the sum bypositions of each letter of the string
nash table is assumed to be 5and so the size of the table. The size of andthe
sothat allthe hash values of while taking the remainder,
all the words liewithin 0 divide the
given by: and 4. So, the hash sum by
H(str) -po t p: t P2...Pn-1 function is
where each p, is the position of
letter in string st.
Data Structures using C-
Thevarious hash values for all the words in the 12.27
given list are shown below:
Words
SI. No
like
Sum of positions hash address sum %S
1. 12+9+ | 5 37
2.
tree
3. 20+18+5+5 48 3
4. you 25+15+21 61
first
5
find
6+9+|8+19+20 72 2
6. 6+9+14+4 33 3
7
place 16+12+|+3+5 =37
9. to 20+15 =35
10. grow 7+18+15+23 =63
11. and 1+14+4 = |9 4
12. then 20+8+5+14 = 47
13. branch 2+18+1+14+3+8 = 46
14. out 15+21+20 =56

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

h[0]. The hash


Observe that hash value of word TO" is 0 and so, it is inserted into the words are
2 and
value of the words LIKE, FIRST', PLACE' and THEN' is scanned. Thus,
inserted into hí21 at the end of the list one by one as and when they are
as shown below:
a hash table can be created. Now, the equivalent code can be written
12.28 Sorting and searching
(represented as arrayof linked lists)
Example 12.17: Insert an itenm into hash table

void insert hash table (int item, NODE aD)

int h value;

hvalue =H(item):

alh_ value]=insert rear (item, alh value|);

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

int search hash table (int key, NODE a[)


int h value;
NODE cur;

h value = H(key); /Find the hash value

cur = search(key, a[h value]); I/Obtain address of searched node


if (cur = NULL)return 0; /Key not found in the list
return l; I/ Key found in the list

Example 12.19: function to display contents of hash table


void display hash table (NODE a(])
int i;
NODE
temp;
for (i =0; i< HASH- SIZE; itt)

printf("a[%d] =", i);


temp = a<i];
Data Structures using C- 12.29
if (temp = NULL)
printf("NULL\n");
else

temp = ali);
while (temp->link != NULL)
printf(%d -->", temp->info);
temp =temp->link:

printf("%dn",temp->info):

into the table and to


the complete program to create a hash table. insert an item
Now,
hash table can be written as shown below:
searchfor a keyinthe
hash table and to search for key
Example 12.20: Cprogram to create
#inchude <stdio.h>
#include <stdlib.h>

#define HASH SIZE 5

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 (: :)

printf("l: Insert 2:Searchn"):;


printf("3: Display 4: Exitln');
printf("Enter the choice :);
scanf("%d", &choice);
Switch (choice)
"%d", &item):
case l:printf(Enter the item: ); scanf(
insert hash table(item, a);
break;
case 2: printf("Enter key item :); scanf("%d", &key);
flag = search hash table (key, a);
if(flag 0)
printf(Key not foundn"):
else
printf("Key foundn"):
break;
case 3: printf("Contents of hash table\n"):
display_hash table(a);
printf("n");
break;
default:exit(0);
E Data Structures using C- 12.31

Address calculation sort


129.
Address Calculation Sort is also called Hush Sort. ln this techniquc, a particular
The
hashing is used. The hashing function hash) should have the property that if
kindof is called
xlZx2, then hash(x 1) s hash(x2). The function which exhibits this property is used
order-preserving or non-decreusing hashing function. If this hashin function item
an item to which sonme previous items have alrcady been
hashed, then this
hash
to
placedin such a way that all the items hashed to a particular valuc should be
is Thus all the items in one sub-file will be
arranged in ascending or descending order. sub-files. When all the items have
equal tothe elements in the subsequent
less than or finally concatenate the items in each
sub-file
this order into sub-files,
been placedin elements. For example, consider the items shown below.
to getthe sorted
43, 84,55, 86
57, 45,36, 91, 28, 79, 35, 68, 89, 20, 62,
where each
available are 0to 9, we use an array of pointers a[10], same.
Since the digits item in the sub-file whose first digit is and
points to the first
Jocation in this array
be obtained by selecting the largest number
Hash value for this problem can significant digit is present. For example, for the
the most
finding at which positionbecause 199 hash
tens position. For the item largest
the digit 4 is in
item 45 hash value is 10 hundredth position. The hash value of a
1 is in
value is 3 since the digit
using the function shown
below:
number can be obtained
find the hash value
Example 12.21: C function to

int hash(int a•], int n)


int big, i, poS;
numbers */
pos = 0; /* Find the largest of all the
for (i= 1; i<n; itt)
if (a[i] > alpos] ) pos =
i;

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));

for( i =j=0; i< 10; itt)


/* Copy from hash table to array */
temp = b[i];
while (temp ! NULL )
alj++] = temp->info;
temp = temp->link;

The C program to sort the


items using Address
below: calculation sort (hash sort) is shown
Data Structures using C- 12.33
:Cprogram to sort using Address Calculation Sort (Hash Sort)
Example12.23:

#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);

printf("Enter the items to sortn"):


create array(a, 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:

for (i= 0; i <HASH SIZE; i++)

a[i].id = 0;
Data Structures using C- 12.35
Computehash value using the function: H(k) - k % m */
intH(intk)

return k % HASH SIZE:

Insertan itemintothe empty slot using linear probing "/


* hash table (int id, char name(], EMPLOYEE af0)
void| insert
int i, index, h value;
h value = H(id);

for (i= 0; i< HASH SIZE: it+)


index = (h value +i)% HASH SIZE:
if(a[index].id ==0) I/ empty slot found

a[index].id = id; / insert employee id


strcpy(a[index].name, name); / insert employee name
break;

fulln"); // No empty slot


if (i = HASH SIZE) printf("Hash table

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)

printf("a[%d] =%d %sn", i, a[i],id, a<i].name);

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;

You might also like