0% found this document useful (0 votes)
193 views16 pages

Task 2 - Hashing and Linear Probing

This document provides source code for a C++ program to implement hash tables using linear probing collision resolution. It defines HashNode and DeletedNode classes to represent nodes in the hash table. It also defines a HashMap class with methods to initialize the hash table array, calculate a hash value using a modulo function, and destructively delete the hash table nodes. The program is successfully compiled and run on Linux to demonstrate basic hash table operations with linear probing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
193 views16 pages

Task 2 - Hashing and Linear Probing

This document provides source code for a C++ program to implement hash tables using linear probing collision resolution. It defines HashNode and DeletedNode classes to represent nodes in the hash table. It also defines a HashMap class with methods to initialize the hash table array, calculate a hash value using a modulo function, and destructively delete the hash table nodes. The program is successfully compiled and run on Linux to demonstrate basic hash table operations with linear probing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIVERSITY OF ENGINEERING AND TECHNOLOGY,

LAHORE

Electrical Department Kala Shah Kaku Campus

Name: Muhammad Faiz Alam Khan


Class: 2016-EE-267
Section: A
Topic: Hashing using Linear Probing
Supervisor: Dr. Bilal Wajid
Table of Contents

Sr. No Topic Page Number

1 Introduction to Hashing 3

2 Examples of Hashing 4

Introduction to Linear
3 5
Probing and Examples

C++ Program to
4 Implement Hash Tables 8
with Linear Probing

5 Exercise 15

6 Solution Attached in Separate file


Hashing

Hashing is an improvement in search Algorithm. It’s one step one step further by
building a data structure that can be searched in O(1) time.

Lets deal with a problem for better Understanding of Hashing.

Suppose we are storing employee records, the primary key for which is employee’s
telephone number

Telephone Name City Department


00923204161968 Faiz Alam Ashrdige Castle Electrical
00923085319983 Rayyan Saeed London Mechanical
00923164044136 Usman Raza Saif Shefflied Solar

Now For this we would be adding three functions,

1) Inserting New Employee Record


2) Searching for an Employee
3) Deleting Old Employee Record

Now the question is how to implement this problem in such a way that all the three
given operations are done in the most efficient manner.

So the solution can be this that we use an Array. We can store them in an array
but then searching a record will require linear time as we have to go through all the
records until the required one is found. An improvement in search can be made if we
store them in a sorted manner, In that case search can be done using Binary search
which takes O(logn) time but then insertion and deletion becomes costly as we need to
maintain the sorted order.
The next can be this that we can use a Linked list. Here also we require a linear time to
search for a particular record as we need to go through all the records until the required
one is found.
The other approach could be using balanced binary search trees which would ensure
that we reach the complexity of O(logn) for all the three operations.
The Next Method is to use Direct access table. This method provides an efficient
complexity of o(1) for all three operations
Lets see how it looks alike. This is an an example of direct access table. Here
telephone number acts as a key and the value stores the address of the record. These
are the records
This method looks good but it also suffer certain limitation. The first limitation is the
size of table. The extra space required is O(m*10^n), where m is the size of pointer to
the record and n are the digits in the telephone number. The other limitation is the
digits in telephone number can be more than that what our integer value can store.

Lets now come to Hashing, what hashing do. Hashing provides O(1) time on average
for insert, search and delete operation. Well need a Black box that takes a phone
number and convert into less digit number. This Black box would be called as Hash
Function.

So a hash Function maps a big number or string to a small integer that can be used as
index in hash table.
For Example
We define a hash function h(x) which is X modulus 7
H(x)= x mod 7
Where x is our input number
Suppose x= 9864567654
H(x)= 9864567654 mod 7= 4
H(x)= 9854354543 mod 7 = 5

See how our Hash Function is mapping such a big number to a single digit
number.
This function is good but certainly not a good choice to be a hash function.
Let’s Discuss some good properties of a Hash Function.
 The First Property is that the hash function should compute things
Efficiently.
 The Second Property is that the hash function should be uniformly
distribute the keys i.e each table position is equally likely for each key.

Now as we have see the concept of Hashing, now we would further discuss the
concept of Collision.

For the same hash function these are the two examples which yields the same
key i.e is 4,

H(x) = x mod 7
x= 9864567654
H(x)=9864567654 mod 7 = 4

x=9854354542
h(x)= 9854354542 mod 7 = 4

hence a collision can occur for the two telephone numbers, this collision creates
a trouble for our hash function. However, things can be controlled, we can
handle this collision and for which we have various techniques of Hashing.
1) Open Addressing: In this we devise methods so that all the elements are
stored in the hash table itself. Open addressing is divided into three types
a. Linear Probing
b. Double Hashing
c. Quadratic Hashing

2) Chaining: The idea to make each cell of hash table point to a linked list of
records that that have same hash function value.
Linear Probing

Linear Probing is a strategy for resolving collisions or keys that map to the
same idex in a Hash Table.

Strategy:

1) Use a hash Function to find the index for a Key.


2) If that spot contains a value, use the next available spot “ a higher index” if
you reach the end of array, go back to the front of the array

Example:

Insert the following number into a Hash Table of size 5 using the hash
function H (key)= Key mod 5. Show the results when the collision is
Resolved.

Numbers: 10, 11, 12, 15

Answer:

Now we are to create a Hash Table. The size of the table would be 5

0 1 2 3 4

Now we are going to take these keys and we are going to plug them into our
hash function.

So,
H(10)= 10 mod 5 = 0
H(11)= 11 mod 5 = 1
H(12)= 12 mod 5 = 2
H(15)= 15 mod 5 = 0
As we can see that collision has occurred, as we have same index for 10 and
15, which is zero.

Now we are going to follow the Linear Probing strategy.


So the linear Probing says use a hash Function to find the index for a key, which
we have done already. So we are going to Step 2, which is if that spot contains a
value, use the next available spot “a higher index” if you reach the end of array,
go back to the front of the array.

So in this the next index would be 1, but as we see it is already contains the
value 11, so we go to the next index that is 2 and we see that it contains 12, so
we go to the next index that is 3. We see that it does not contain a value so we
can put our key in that new spot there and so we put our key which is 15 into
the index 3 and that solves this Collison Problem.

10 11 12 15
0 1 2 3 4
C++ Program to Implement Hash Tables with Linear Probing

This C++ Program demonstrates operations on Hash Tables with Linear Probing.
Here is source code of the C++ Program to demonstrate Hash Tables with Linear Probing. The C+
+ program is successfully compiled and run on a Linux system. The program output is also shown
below.

1. /*
2.  * C++ Program to Implement Hash Tables with Linear Probing
3.  */
4. #include <iostream>
5. #include <cstdio>
6. #include <cstdlib>
7. using namespace std;
8. const int TABLE_SIZE = 5;
9.  
10. /*
11.  * HashNode Class Declaration
12.  */
13. class HashNode
14. {
15. public:
16. int key;
17. int value;
18. HashNode(int key, int value)
19. {
20. this->key = key;
21. this->value = value;
22. }
23. };
24.  
25. /*
26.  * DeletedNode Class Declaration
27.  */
28. class DeletedNode:public HashNode
29. {
30. private:
31. static DeletedNode *entry;
32. DeletedNode():HashNode(-1, -1)
33. {}
34. public:
35. static DeletedNode *getNode()
36. {
37. if (entry == NULL)
38. entry = new DeletedNode();
39. return entry;
40. }
41. };
42. DeletedNode *DeletedNode::entry = NULL;
43. /*
44.  * HashMap Class Declaration
45.  */
46. class HashMap
47. {
48. private:
49. HashNode **htable;
50. public:
51. HashMap()
52. {
53. htable = new HashNode* [TABLE_SIZE];
54. for (int i = 0; i < TABLE_SIZE; i++)
55. {
56. htable[i] = NULL;
57. }
58. }
59.  
60. ~HashMap()
61. {
62. for (int i = 0; i < TABLE_SIZE; i++)
63. {
64. if (htable[i] != NULL && htable[i] != DeletedNode::getNode())
65. delete htable[i];
66. }
67. delete[] htable;
68. }
69. /*
70.   * Hash Function
71.   */
72. int HashFunc(int key)
73. {
74. return key % TABLE_SIZE;
75. }
76. /*
77.   * Insert Element at a key
78.   */
79. void Insert(int key, int value)
80. {
81. int hash_val = HashFunc(key);
82. int init = -1;
83. int deletedindex = -1;
84. while (hash_val != init && (htable[hash_val]
85. == DeletedNode::getNode() || htable[hash_val]
86. != NULL && htable[hash_val]->key != key))
87. {
88. if (init == -1)
89. init = hash_val;
90. if (htable[hash_val] == DeletedNode::getNode())
91. deletedindex = hash_val;
92. hash_val = HashFunc(hash_val + 1);
93. }
94. if (htable[hash_val] == NULL || hash_val == init)
95. {
96. if(deletedindex != -1)
97. htable[deletedindex] = new HashNode(key, value);
98. else
99. htable[hash_val] = new HashNode(key, value);
100. }
101. if(init != hash_val)
102. {
103. if (htable[hash_val] != DeletedNode::getNode())
104. {
105. if (htable[hash_val] != NULL)
106. {
107. if (htable[hash_val]->key == key)
108. htable[hash_val]->value = value;
109. }
110. }
111. else
112. htable[hash_val] = new HashNode(key, value);
113. }
114. }
115. /*
116.  * Search Element at a key
117.  */
118. int Search(int key)
119. {
120. int hash_val = HashFunc(key);
121. int init = -1;
122. while (hash_val != init && (htable[hash_val]
123. == DeletedNode::getNode() || htable[hash_val]
124. != NULL && htable[hash_val]->key != key))
125. {
126. if (init == -1)
127. init = hash_val;
128. hash_val = HashFunc(hash_val + 1);
129. }
130. if (htable[hash_val] == NULL || hash_val == init)
131. return -1;
132. else
133. return htable[hash_val]->value;
134. }
135. /*
136.  * Remove Element at a key
137.  */
138. void Remove(int key)
139. {
140. int hash_val = HashFunc(key);
141. int init = -1;
142. while (hash_val != init && (htable[hash_val]
143. == DeletedNode::getNode() || htable[hash_val]
144. != NULL && htable[hash_val]->key != key))
145. {
146. if (init == -1)
147. init = hash_val;
148. hash_val = HashFunc(hash_val + 1);
149. }
150. if (hash_val != init && htable[hash_val] != NULL)
151. {
152. delete htable[hash_val];
153. htable[hash_val] = DeletedNode::getNode();
154. }
155. }
156.};
157. 
158./*
159. * Main Contains Menu
160. */
161.int main()
162.{
163. HashMap hash;
164. int key, value;
165. int choice;
166. while(1)
167. {
168. cout<<"\n----------------------"<<endl;
169. cout<<"Operations on Hash Table"<<endl;
170. cout<<"\n----------------------"<<endl;
171. cout<<"1.Insert element into the table"<<endl;
172. cout<<"2.Search element from the key"<<endl;
173. cout<<"3.Delete element at a key"<<endl;
174. cout<<"4.Exit"<<endl;
175. cout<<"Enter your choice: ";
176. cin>>choice;
177. switch(choice)
178. {
179. case 1:
180. cout<<"Enter element to be inserted: ";
181. cin>>value;
182. cout<<"Enter key at which element to be inserted: ";
183. cin>>key;
184. hash.Insert(key, value);
185. break;
186. case 2:
187. cout<<"Enter key of the element to be searched: ";
188. cin>>key;
189. if(hash.Search(key) == -1)
190. {
191. cout<<"No element found at key "<<key<<endl;
192. continue;
193. }
194. else
195. {
196. cout<<"Element at key "<<key<<" : ";
197. cout<<hash.Search(key)<<endl;
198. }
199. break;
200. case 3:
201. cout<<"Enter key of the element to be deleted: ";
202. cin>>key;
203. hash.Remove(key);
204. break;
205. case 4:
206. exit(1);
207. default:
208. cout<<"\nEnter correct option\n";
209. }
210. }
211. return 0;
212.}

Output
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 100
Enter key at which element to be inserted: 1
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 300
Enter key at which element to be inserted: 3
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 500
Enter key at which element to be inserted: 5
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 600
Enter key at which element to be inserted: 6
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 800
Enter key at which element to be inserted: 8
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 1000
Enter key at which element to be inserted: 10
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 3
Element at key 3 : 300
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 7
No element found at key 7
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 10
Element at key 10 : 1000
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 3
Enter key of the element to be deleted: 5
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 6
Element at key 6 : 600
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 5
No element found at key 5
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 1
Enter element to be inserted: 700
Enter key at which element to be inserted: 7
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 2
Enter key of the element to be searched: 7
Element at key 7 : 700
 
----------------------
Operations on Hash Table
 
----------------------
1.Insert element into the table
2.Search element from the key
3.Delete element at a key
4.Exit
Enter your choice: 4
 
------------------
(program exited with code: 1)

Exercise

1) Search, Insert and Delete using linear probing in C++


2) Given the values {2341, 4234, 2839, 430, 22, 397, 3920}, a hash table of size 7, and hash
function h(x) = x mod 7, show the resulting tables after inserting the values in the given
order with each of these collision strategies.
3) Suppose you need to insert unique 3-character IDs into a hash table, where each ID is
made up of some combination of two of the capital letters A-D, followed by one of the
lower case letters x-z, such as: ABx, DCy, BBz, etc. Repeat letters are allowed in an ID
4) Suppose a hash table with capacity M=31 gets to be over 3/4ths full. We decide to rehash.
What is a good size choice for the new table to reduce the load factor below .5 and also
avoid collisions?
5) Suppose you are running a food service business which has special promotions for
frequent customers. Each month you send out discount offers to different groups based on
their spending in your establishment. For example, one month those who spent $25-50
might get a free drink coupon, or another month those who spent $50-100 might get a 2-
for-1 lunch offer. The spending ranges will change each month, and you want to be able to
find the right group of people each month in O(K + log N) time, where K is the size of the
group and N is the total number of customers. What data structure(s) would you choose
and how would you implement a solution to this problem?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy