1
\$\begingroup\$

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.

asked Dec 3, 2016 at 15:48
\$\endgroup\$
1
  • 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\$ Commented Dec 3, 2016 at 16:38

1 Answer 1

2
\$\begingroup\$
  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 the hash word to their names (except for the one that actually computes the hash)? hashSearch and addToHash make it sound like the code looks for/adds a hash. It doesn't. It adds/searches for the value.

  2. 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 a boolean value (and I'd call it something like contains).

  3. 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.

answered Dec 3, 2016 at 15:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.