Ds 5 Update
Ds 5 Update
1 1 1 % 20 = 1 1
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 2
4 4 4 % 20 = 4 4
5 12 12 % 20 = 12 12
6 14 14 % 20 = 14 14
7 17 17 % 20 = 17 17
8 13 13 % 20 = 13 13
9 37 37 % 20 = 17 17
HASH TABLE
A hash table is a data structure that is used
to store keys/value pairs.
It uses a hash function to compute an index
work well.
Let us consider string S. You are required to
Output
a2
b2
c1
d1
e0
f0
…
z0
BASIC OPERATIONS
table.
Insert − inserts an element in a hash table.
table.
APPLICATIONS
value is computed and then the array is examined (starting with the
hashed index).
If the slot at the hashed index is unoccupied, then the entry record is
The name "open addressing" refers to the fact that the location or
(usually to 1).
Let’s assume that the hashed index for a particular entry is index. The
probing sequence for linear probing will be:
index = index % hashTableSize
index = (index + 1) % hashTableSize
index = (index + 2) % hashTableSize
IMPLEMENTATION OF HASH TABLE WITH
LINEAR PROBING
Assumption
There are no more than 20 elements in the data set.
Hash function will return an integer from 0 to 19.
Data set must have unique elements.
string hashTable[21];
int hashTableSize = 21;
Insert
void insert(string s)
{
//Compute the index using the hash function
int index = hashFunc(s);
//Search for an unused slot and if the index will exceed
the hashTableSize then roll back
while(hashTable[index] != "")
index = (index + 1) % hashTableSize;
hashTable[index] = s;
}
Search
void search(string s)
{
//Compute the index using the hash function
int index = hashFunc(s);
//Search for an unused slot and if the index will exceed
the hashTableSize then roll back
while(hashTable[index] != s and hashTable[index] !=
"")
index = (index + 1) % hashTableSize;
//Check if the element is present in the hash table
if(hashTable[index] == s)
cout << s << " is found!" << endl;
else
cout << s << " is not found!" << endl;
}
QUADRATIC PROBING
Quadratic probing is similar to linear probing and the only
difference is the interval between successive probes or
entry slots.
when the slot at a hashed index for an entry record is
string hashTable[21];
int hashTableSize = 21;
Insert
void insert(string s)
{
//Compute the index using the hash function1
int index = hashFunc1(s);
int indexH = hashFunc2(s);
//Search for an unused slot and if the index exceeds the
hashTableSize roll back
while(hashTable[index] != "")
index = (index + indexH) % hashTableSize;
hashTable[index] = s;
}
Search
void search(string s)
{
//Compute the index using the hash function
int index = hashFunc1(s);
int indexH = hashFunc2(s);
//Search for an unused slot and if the index exceeds the
hashTableSize roll back
while(hashTable[index] != s and hashTable[index] != "")
index = (index + indexH) % hashTableSize;
//Is the element present in the hash table
if(hashTable[index] == s)
cout << s << " is found!" << endl;
else
cout << s << " is not found!" << endl;
}