You are on page 1of 4

CS 201 Data Structures – Hash Tables Tutorial 01

1)
A)
 Insertion and searching operations are very fast.
 Can store large number of data.

B) public int hashFuntion(int value){


int index = value % 8;
return index;
}

C) Good hash function must include following features,


 Hash function generated should not be complex.
 Should provide uniform distribution across hash table.
 Less number of collisions.

2)
A) public int hashFunction(String s){
int index=0;
for(int i=0;i<s.length();i++)
{
index = index + charAt(i);
}
index = index % 599;
return index;
}
According to the above hash function all the strings get same index,
abcedf index = (97+98+99+100+101+102) % 599 = 2,
bcdefa index = (98+99+100+101+102+97) % 599 = 2,
cedfab index = (99+100+101+102+97+98) % 599 = 2,
efabcd index = (100+101+102+97+98+99) % 599 = 2,

B)
Hash function = (sum of ASCII values + position of letter a + position of letter b) %
number of elements

According to this hash function indexes are calculated as below,


“abcdef” index = (97+98+99+100+101+102+1(position of a)+ 2(position of b)) % 4 = 0
“bcdefa” index = (98+99+100+101+102+97+6(position of a)+ 1(position of b)) % 4 = 1
“cdefab” index = (99+100+101+102+97+98+5(position of a)+ 6(position of b)) % 4 = 2
“defabc” index = (100+101+102+97+98+99+4(position of a)+ 5(position of b)) % 4 = 3

C)
To avoid collision we can use linear probing methods. According to this method
when we get already used array index that element is looking into next cell until find
empty cell.
When consider the above case,
Array -> before linear probing
“abcdef”
“bcdefa”
“cdefac”
“defabc”
0 1 2 3 4 5

Element “abcdef” index is 2. Therefore it insert to 2 cell.


Element “cdefa” index is 2. But that cell already filled. Therefore this element shift to
the next cell(index = 3 cell). It is empty and “bcdefa” insert to it.
Element “cdefab” index is 2. It is filled. Shift to the next cell (index = 3 cell). It also
filled. Therefore shift to next(index = 4 cell). It is empty and “cdefab” insert to it.
Element “defabc” index is 2. Then shift along the array until find empty cell. The
empty cell is index=5 cell and element insert to it.

Array -> after linear probing


“abcdef” “bcdefa” “cdefab” “defabc”

0 1 2 3 4 5

3)
A)
Hash Function = value % 8,
According to this the indexes for each value is,

value hash function index


119 119 % 8 7
123 123 % 8 3
145 145 % 8 1
117 117 % 8 5
115 115 % 8 3
138 138 % 8 2
120 120 % 8 0
135 135 % 8 7

Array -> before linear probing


120 145 138 123 117 119
115 135
0 1 2 3 4 5 6 7
Array -> after linear probing
120 145 138 123 115 117 119 135

0 1 2 3 4 5 6 7 8

B)
When using chaining method element list implement as a linked list array. The
elements which have same index insert to same cell as a linked list,
0 1 2 3 4 5 6 7
120 145 138 123 117 119

115 135

You might also like