I'm trying to find a way to make my algorithm execute faster. What this function is currently doing is inserting values(chars) and keys(strings) into my hashtable with 7 slots. It is also running checks to see if A. there is something occupying it's optimal slot, and then placing it in the best available spot. And B. If 2 identical keys are inserted, the new key simply transfers it's value to the old key instead of taking up a new slot by itself. Is there any way to do this without iterating my "keys" array?
public void put(String key, Character val) {
int z = hash(key);
while(keys[z] != null){
if(key.equals(keys[z])){
vals[z]= val;
break;
}
z ++;
if (z>6){
z=0;
if(key.equals(keys[z])){
vals[z]= val;
break;
}
if(keys[0]==null){
break;
}
else{
z++;
}
}
}
keys[z] = key;
vals[z] = val;
N += 1;
}
update: This is my hash() function
public int hash(String key) {
int i;
int v = 0;
for (i = 0; i < key.length(); i++) {
v += key.charAt(i);
}
return v % M;
}
If I understand your code right you have an open-addressed hash table with linear probing .
Alternatives for linear probing (your loop where you're searching for an empty spot) are:
But anyway worst-case time will be linear. And for a very small table with only 7 elements your linear approach with increments by 1 looks fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.