TCP2101 Algorithm Design and Analysis Lab02 - HashTables
TCP2101 Algorithm Design and Analysis Lab02 - HashTables
Lab 2 HashTables
Learning Outcomes
● Understand HashTable ADT
● Use chaining and linear probing to resolve collision.
1. Hashtable ADT: The following sequence of 10 numbers are inserted into a hash table using
hash function h(k) = k % 11.
(a) (30 min) If chaining is used to resolve collision, how does the hashtable look like? Fill up
the h(k) value in the table below.
k 36 99 80 21 58 11 25 46 91 10
h(k) 36% 99% 80% 21 % 58 % 11 % 25 % 46 % 91 % 10 %
11 = 11 = 11 = 11 = 11 = 11 = 11 = 11 = 11 = 11 =
3 0 3 10 3 0 3 2 3 10
Collision N N Y N Y Y Y N Y Y
(Y/N)
0 -> 11 -> 99
1 ->
2 -> 46
3 -> 91 -> 25 -> 58 -> 80 -> 36
4 ->
5 ->
6 ->
7 ->
8 ->
9 ->
10 -> 10 -> 21
(b) (30 min) If linear probing is used to resolve collisions. What does the hashtable look like?
Fill up the h(k) value in the table below.
k 36 99 80 21 58 11 25 46 91 10
h(k) 3 0 3 10 3 0 3 2 3 10
No of 0 0 1 0 2 1 3 0 4 9
Collision
k 99 11 46 36 80 58 25 91 10 21
probe 0 1 0 0 1 2 3 4 9 0
index 0 1 2 3 4 5 6 7 8 9 10
1
2. An incomplete C++ implementation of Hashtable ADT with chaining is provided below.
(a) (20 min) Complete the insert function and retrieve function in the HashTable class. Use
the LinkedList.cpp from tutor.
// HashTable.cpp
#include <vector>
#include "LinkedList.cpp" // get from tutor
}
bool retrieve (T & target) {
int location = hashfunction(target);
if (!table[location].find(target)//type ife ctrl+j
{
return false;
}
else
{
return true;
}
// bool found = table[index].find(target);
//return found;
}
friend ostream& operator<< (ostream& os, HashTable<T>& ht) {
for (int i = 0; i < ht.size(); i++)
os << i << " = " << ht.table[i] << endl;
return os;
}
};
2
(b) (20 min) Complete the following program that uses the above HashTable class. Verify that
the program output is correct.
int main() {
const int n = 10;
int A[n] = {36, 99, 80, 21, 58, 11, 25, 46, 91, 10};
// 2. Declare a hashtable of int named "ht", size is 11.
HashTable<int> ht(11); //<int> is to support integer datatype
// Display ht.
cout << ht << endl;
int target;
cout << "Target to retrieve: ";
cin >> target;
// 4. Retrieve the target from ht.
if (ht.retrieve(target))
cout << "Target found\n";
else
cout << "Target not found\n";
}
(c) (10 min) Count the number of primitive operations of each step in LinkedList’s insertFront
function. What is its time complexity?
3
(d) (10 min) Count the number of primitive operations of each step in LinkedList’s find function.
What is its time complexity?