Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Hash {
- // double count = 0;
- int[] hTable = new int[7]; // Create a new hash table with a specified size
- public Hash() { // Constructor?
- }
- public void add(int key) { // no return, pass in an integer value
- int address = key % hTable.length; // Set the address = the key mod the table size
- // hTable[key] = (key/hTable.length);
- // int y = (int) ((count / hTable.length) * 100);
- // if (y > 80) {
- // System.out.println("Table has reached its maximum load factor of 80%");
- // } else {
- if (hTable[address] == 0) // Check to see if the index is empty
- hTable[address] = key; // If it is, add the key to the index
- else {
- while (hTable[address] != 0) { // Otherwise, while there is a collision
- if ((key / hTable.length) % hTable.length == 0) // If the key div table size mod table size is zero
- address += 1; // add 1 to the current address
- else {
- address += (key / hTable.length); // Otherwise, set the address += to the key div table size
- if (address > hTable.length-1) // If the address is larger than the last index value
- address = (address % (hTable.length)) - 1; // mod it back to zero
- }
- }
- hTable[address] = key; // Add the key to the index
- }
- // count++;
- // }
- }
- public int find(int key) { // return int, pass in an integer value
- int address = key % hTable.length; // Set the address = the key mod the table size
- if (hTable[address] == 0) { // If the key cannot be found in the table
- return -1; // return -1 to indicate that it could not be found
- }
- if (hTable[address] == key) { // If the address contains the key, return the address
- return address;
- } else {
- while (hTable[address] != key) { // Otherwise, while the address does not contain the key
- address += (key / hTable.length); // Search the table by setting the address += to the key div table size
- if (address > hTable.length) // If it tries to search outside the table,
- address = (address % (hTable.length)) - 1; // reset the address back to zero
- }
- }
- return address; // When you are done, return the address
- }
- public String toString() { // toString Method
- String s = "";
- for (int i = 0; i < hTable.length; i++) {
- s += "\n[" + i + "," + hTable[i] + "]";
- }
- return s;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement