CSCE 146
Lab 12
In this lab we’ll examine Hashing techniques
and how to resolve collisions during hashing.
1. Write
a class PrimeTest, that tests
whether a given number is prime or not. Implement a method with the following
signature :
Public Boolean isPrime(int n)
{
//method
implementation
}
A simple method of determining the
primality of a number N is to
check whether it is divisible by any number between 2 and the ÖN. In
case N is not divisible by any such number, it is a prime.
2. Download
the Table
class from Michael Maine’s website. This class implements a Hash Table based
on Open Address hashing with Linear Probing. Also, make sure that you have the
file ‘newfile.dat’ containing student data, in the same folder. Now,
write a class TableTest, in
which you invoke the constructor of
the Table class to create
a Table object. Use the PrimeTest class that you wrote in step
1 to set the size of the table to
a prime number p, such that :
1000 < p < 1500 and
p = 4k + 3 where k is an integer.
Now write
a method to read in student data
from the file, and insert student objects into the Hash Table. The pseudo-code
for this is given below:.
while (there is more data in the file
‘newfile.dat’)
{
Read data
corresponding to the next student.
Instantiate a
Student object with this data.
Add the Student
object to the Hash Table.
}
3. Solve
the programming project # 6 on page 565 of your text book. Add suitable class variables and methods to the Table class so that you
can obtain the statistics mentioned in the project. In the TableTest class, search the Table for
a student that already exists in the Table, and print out the statistics
obtained.
4. Now,
modify the Table class to implement
Double Hashing. To do so, we first we need to find a pair of twin primes in the
range (1000 - 1500), using the PrimeTest class. Next, replace the
private hash() method of the
Table class with two methods hash1()
and hash2(). Define these
methods as follows :
hash1(key) =
Math.abs(key.hashCode()) % data.length
hash2(key) = 1 +
Math.abs(key.hashCode()) % (data.length – 2)).
You will
also need to modify the put()
method of the Table class to use
double hashing to resolve collisions.
Use the same tests that you
ran in step 3 and print out the statistics for Double Hashing. Compare these
with the statistics that you obtained previously for Linear Probing.
Enjoy!!