Advertisement
Guest User

Untitled

a guest
Aug 12th, 2017
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. public class Hash {
  2. // double count = 0;
  3. int[] hTable = new int[7]; // Create a new hash table with a specified size
  4.  
  5. public Hash() { // Constructor?
  6. }
  7.  
  8. public void add(int key) { // no return, pass in an integer value
  9. int address = key % hTable.length; // Set the address = the key mod the table size
  10. // hTable[key] = (key/hTable.length);
  11. // int y = (int) ((count / hTable.length) * 100);
  12. // if (y > 80) {
  13. // System.out.println("Table has reached its maximum load factor of 80%");
  14. // } else {
  15. if (hTable[address] == 0) // Check to see if the index is empty
  16. hTable[address] = key; // If it is, add the key to the index
  17. else {
  18. while (hTable[address] != 0) { // Otherwise, while there is a collision
  19. if ((key / hTable.length) % hTable.length == 0) // If the key div table size mod table size is zero
  20. address += 1; // add 1 to the current address
  21. else {
  22. address += (key / hTable.length); // Otherwise, set the address += to the key div table size
  23. if (address > hTable.length-1) // If the address is larger than the last index value
  24. address = (address % (hTable.length)) - 1; // mod it back to zero
  25. }
  26. }
  27. hTable[address] = key; // Add the key to the index
  28. }
  29. // count++;
  30. // }
  31. }
  32.  
  33. public int find(int key) { // return int, pass in an integer value
  34. int address = key % hTable.length; // Set the address = the key mod the table size
  35. if (hTable[address] == 0) { // If the key cannot be found in the table
  36. return -1; // return -1 to indicate that it could not be found
  37. }
  38. if (hTable[address] == key) { // If the address contains the key, return the address
  39. return address;
  40. } else {
  41.  
  42. while (hTable[address] != key) { // Otherwise, while the address does not contain the key
  43. address += (key / hTable.length); // Search the table by setting the address += to the key div table size
  44. if (address > hTable.length) // If it tries to search outside the table,
  45. address = (address % (hTable.length)) - 1; // reset the address back to zero
  46. }
  47. }
  48. return address; // When you are done, return the address
  49. }
  50.  
  51. public String toString() { // toString Method
  52. String s = "";
  53. for (int i = 0; i < hTable.length; i++) {
  54. s += "\n[" + i + "," + hTable[i] + "]";
  55. }
  56. return s;
  57. }
  58.  
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement