//implement other functions: rehashing and findprime public static void main() {
ID: 3905874 • Letter: #
Question
//implement other functions: rehashing and findprime
public static void main() {
MyHashTable hashtable = new MyHashTable(11);
System.out.println(hashtable.hash(5));
for(int i = 1; i <= 4; i++)
hashtable.put(11*i, 11*i*10);
hashtable.printArray();
for(int i = 1; i <= 4; i++)
System.out.println(hashtable.get(11*i));
//when i = 5, rehashing function should be called automatically from put function
//because hashtable has 5 items, m/2 = 11/2 = 5
//the size of new hashtable should be 23
for(int i = 5; i <= 10; i++)
hashtable.put(11*i, 11*i*10);
hashtable.printArray();
//put into the hashtable with more items
//you can generate your own version of key-value pairs, do not have to (11*i, 11*i*10)
//note that all keys and values must be nonzero, it is important.
//because in this homework, we are assuming 0 as the empty bucket.
}
}
Explanation / Answer
public int findPrime(int a){
int prime = 0;
while(prime == 0){
a = a + 1;
prime = 1;
for (int i = 2; i < a; i++){
if (a % i == 0)
prime = 0;
}
}
return a;
}
public void rehashing(){
int n1 = findPrime(2*m);
int[] newkeys = new int[n];
int[] newvalue = new int[n];
int[] tempkeys = new int[m];
int[] tempvalues = new int[m];
for (int i = 0; i<m; i++){
tempkeys[i] = keys[i];
tempvalues[i] = values[i];
}
k = m;
keys = newkeys;
values = newvalues;
m = n1;
n = 0;
for (int i = 0; i<k; i++){
put(tempkeys[i],tempvalues[i]);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.