I am seeking a review of a previous project I completed to help understand hash tables.
The following is my implementation of a hash-table using linear probing.
My solution assumes a number of variables have been initialised:
- Private int[] H; Representing the hash table with each value initialised to -1
- private int hSize; Storing the size of the hash table
Hash Function:
public int hash(int key){
return key % hSize;
}
Add value to hash table:
private void addToHash(int value){
int i;
for (i = hash(value); H[i] != -1; i = (i + 1) % H.length)
if (H[i] == value) return;
H[i] = value;
}
Search for value:
public int hashSearch(int key){
int hash = hash(key);
for (int i = hash; H[i] != -1; i = (i + 1) % H.length)
if (H[i] == key) return i;
return -1;
}
I am looking for feedback regarding the design of my solution / programming style - Anything which could be improved in the future or would not be encouraged when programming in the industry.
-
1\$\begingroup\$ I think this question could benefit from including the complete class rather than a subset of its operations as shown by kraskevich's answer. \$\endgroup\$jacwah– jacwah2016年12月03日 16:38:20 +00:00Commented Dec 3, 2016 at 16:38
1 Answer 1
The method names are a little bit misleading. They're already in the
HashTable
class, aren't they? If yes, then why would you add thehash
word to their names (except for the one that actually computes the hash)?hashSearch
andaddToHash
make it sound like the code looks for/adds a hash. It doesn't. It adds/searches for the value.What does the
hashSearch
return? The index is the internal implementation detail. I do not see a good reason to expose it to the client. It should probably return aboolean
value (and I'd call it something likecontains
).You did not present the full code, so there are a lot of questions left. What is the initial number of buckets in the table? Does it grow? What happens if it gets fully loaded (the
addToHash
method can stuck in an infinity loop in that case)? These questions are very important, but, unfortunately, I can't comment on those as the relevant parts of your code are missing.