Question

Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). )

  1. When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases).

Theory answer Here

  1. Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This dramatically simplifies the implementation because there is no collision resolution, you just add to the linkedlist, and search now goes to the index and then does a linear search. ( my submission is below,, feel free to make changes or create something new!)


    public class hashtable
    {

    //inner class hash entry to be added to hash table
    class hashentry
    {
    int key;
    string data;

    //setters and getters
    public hashentry(int key, string data)
    {
    this.key = key;
    this.data = data;
    }
    public int getkey()
    {
    return key;
    }
    public string getdata()
    {
    return data;
    }
    }


    int maxSize; // table length
    hashentry[] table; //create array of hash entries

    /*
    *
    *Hash table constructor given size paramter to set the length of the array

    *set table to null
    */

    public hashtable(int size)
    {
    maxSize = size;
    table = new hashentry[size];
    for (int i = 0; i < size; i++)
    {
    table[i] = null;
    }
    }

    /*
    * using key, get element at given key parameter, return key to string
    */
    public string retrieve(int key)
    {
    int hash = key % maxSize;
    while (table[hash] != null && table[hash].getkey() != key)
    {
    hash = (hash + 1) % maxSize;
    }
    if (table[hash] == null)
    {
    return "nothing found!";
    }
    else
    {
    return table[hash].getdata();
    }
    }

    /*
    * using string data, get element at given string if it is exact, return hash entry to console
    */
    public void retrievedata(string data)
    {
    for (int i = 1; i <= table.Length; i++)
    {
    try
    {
    if (table[i].getdata().Equals(data) && table[i].getdata() != null && table != null && i <= maxSize)//if we have null entries
    {

    Console.WriteLine("Key value :{0} , Data Value :{1}, Length of Data : {2}", table[i].getkey(), table[i].getdata(), table[i].getdata().Length);
    }
    else
    {
    continue;
    }
    }
    catch { }
    }
    }

    /*
    * checks for open spaces in the table for insertion method
    */

    private bool checkOpenSpace()//checks for open spaces in the table for insertion
    {
    bool isOpen = false;
    for (int i = 0; i < maxSize; i++)
    {
    if (table[i] == null)
    {
    isOpen = true;
    }
    }
    return isOpen;
    }


    /*
    * Method to print all elements of the hash array
    * Print all iterates over all the n elements in the container, so it is o(n) operation.
    */

    public void print()
    {
    for (int i = 0; i < table.Length; i++)
    {
    if (table[i] == null && i <= maxSize)//if we have null entries
    {
    continue;//dont print them, continue looping
    }
    else
    {
    Console.WriteLine("Key value :{0} , Data Value :{1}, Length of Data : {2}", table[i].getkey(), table[i].getdata(), table[i].getdata().Length);
    }
    }
    }

    /*
    *Quadratic probe insert is in best case o(1) when location of the hash is empty and in worst
    * case o(n) when it is not empty, so you must loop until you find one that is.
    * if quadratic probe insert is not necessary, it needs to change the pointer to the hash so it is o(1)
    */

    public void quadraticHashInsert(int key, string data)
    {
    // quadratic probing method
    if (!checkOpenSpace())//if no open spaces available
    {
    Console.WriteLine("table is at full capacity!");
    return;
    }

    int j = 0;
    int hash = hash1(key);
    if (hash >= 0)
    {
    while (table[hash] != null && table[hash].getkey() != key && hash>=0)
    {
    j++;
    hash = (hash + j * j) % maxSize;

    // hash = (hash + j * j) % maxSize;
    }

    if (table[hash] == null)
    {
    table[hash] = new hashentry(key, data);
    return;
    }
    }

    }
    private int hash1(int key)
    {
    return key % maxSize;
    }
    private int hash2(int key)
    {
    //must be non-zero, less than array size, ideally odd
    return 5 - key % 5;
    }
    }
    }
    )

Code and Testing here

  1. Theory discussion: Don’t try and derive a formal maths answer here, but when should you “grow” on a hashtable like the one in B, given that you no longer really have a load factor as in a regular hash table?

Theory here



0 0
Add a comment Improve this question Transcribed image text
Answer #1

Usually we insert into the hash table using key% array_size, however if we insert the values using:

key%array_size*2. there would be less collision since our bucket size now become doubles and thus, there are less chances of collision.

But if we insert using key%array_size/2, the bucket size reduced to half and thus as the size decreases, there would be more collision, Hence more time would be required to fetch the value during retrieval.

For example:

lets take the numbers : 5 , 20, 16, 10, 4

The hash table will be if we insert using key%array_size ( 0,1,2,3,4 in the leftmost side are the index of array of size 5)

0 --> 5 --- 20 --- 10

1 --> 16

2 -->

3 -->

4 --> 4

The hash table will be if we insert using key%array_size*2

0 --> 20 --- 10

1 -->

2 -->

3 -->

4 --> 4

5 --> 5

6 --> 16

7 -->

8 -->

9 -->

The hash table will be if we insert using key%array_size/2 ( since array_size= 5 , therefore 5/2=2 (taking floor value)

0 --> 20 ---16 ---10 --- 4

1 --> 5

Add a comment
Know the answer?
Add Answer to:
Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Identify the letters and anything associated with it. It is a hash map so please feel...

    Identify the letters and anything associated with it. It is a hash map so please feel free to point out the other important parts beside the arrows. I apologize for the order of the pictures class HashMap private: HashEntry table ; public: HashMap() table-new HashEntry * [TABLE_SIZE]; for (int 1-0; 1< TABLE SIZE: i++) table [i] = NULL; Hash Function int HashFunc(int key) return key % TABLE-SIZE; Insert Element at a key void Insert(int key, int value) int hashHashFunc(key); while...

  • The task of this project is to implement in Java Hash Table structure using Linear Probing...

    The task of this project is to implement in Java Hash Table structure using Linear Probing Collision Strategy.   You can assume that no duplicates or allowed and perform lazy deletion (similar to BST). Specification Create a generic class called HashTableLinearProbe <K,V>, where K is the key and V is the value. It should contain a private static class, HashEntry<K,V>. Use this class to create array to represent Hashtable:             HashEntry<K,V> hashtable[]; Implement all methods listed below and test each method...

  • Write a method in the HashIntSet class called addAll that accepts another hash set as a...

    Write a method in the HashIntSet class called addAll that accepts another hash set as a parameter and adds all of the elements from the other set into the current set. For example, if the set stores [-5, 1, 2, 3] and the method is passed [2, 3, 6, 44, 79], your set would store [-5, 1, 2, 3, 6, 44, 79]. Write a method in the HashIntSet class called containsAll that accepts another hash set as a parameter and...

  • I need help fixing my java code for some reason it will not let me run...

    I need help fixing my java code for some reason it will not let me run it can someone pls help me fix it. class LinearProbingHashTable1 { private int keyname; private int valuename; LinearProbingHashTable1(int keyname, int valuename) { this.keyname = keyname; this.valuename = valuename; } public int getKey() { return keyname; } public int getValue() { return valuename; } } class LinearProbingHashTable2 { private final static int SIZE = 128; LinearProbingHashTable2[] table; LinearProbingHashTable2() { table = new LinearProbingHashTable2[SIZE]; for (int...

  • JAVA Submit:    HashSet.java    with the following methods added: HashSet.java // Implements a set of...

    JAVA Submit:    HashSet.java    with the following methods added: HashSet.java // Implements a set of objects using a hash table. // The hash table uses separate chaining to resolve collisions. // Original from buildingjavaprograms.com supplements public class HashSet<E> { private static final double MAX_LOAD_FACTOR = 0.75; private HashEntry<E>[] elementData; private int size; // Constructs an empty set. @SuppressWarnings("unchecked") public HashSet() { elementData = new HashEntry[10]; size = 0; } // ADD METHODS HERE for exercise solutions: // Adds the...

  • Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function...

    Follow the TODOs and complete the insertItem(), searchItem() and printTable() functions in hash.cpp. The hash function has already been implemented for you. // hash.CPP program to implement hashing with chaining #include<iostream> #include "hash.hpp" using namespace std; node* HashTable::createNode(int key, node* next) { node* nw = new node; nw->key = key; nw->next = next; return nw; } HashTable::HashTable(int bsize) { this->tableSize= bsize; table = new node*[tableSize]; for(int i=0;i<bsize;i++) table[i] = nullptr; } //function to calculate hash function unsigned int HashTable::hashFunction(int key)...

  • Type up and get the Hash table on pages 19 - 22 to work. Show your...

    Type up and get the Hash table on pages 19 - 22 to work. Show your sample test run at the bottom of your code using a multiline comment I typed everything but the code is not working please help me fix the mistakes. These are pages 19-22. The code I have: #include <iostream> #inlcude <iomanip> #include <stack> #include <vector> #include <cstdlib> #include <ctime> using namespace std; //////////////////////////////HASH TABLE/////////////////////////////////////////////// //hash.cpp //demonstrate hash table with linear probing /////////////////////////////////////////////////////////////////////////////////////// class DataItem {...

  • Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow...

    Your task is to go through and implement the methods getBucketIndex, add, get, and remove. Follow the comments inside respective methods. import java.util.ArrayList; import java.util.Scanner; public class HashtableChaining<K, V> {    // Hashtable bucket    private ArrayList<HashNode<K, V>> bucket;    // Current capacity of the array list    private int numBuckets;    // current size of the array list    private int size;       public HashtableChaining(int buckets){        bucket = new ArrayList<>();        numBuckets = buckets;   ...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main...

    JAVA (advanced data structures) write a completed program using HashIntSet and HashMain include the method in the main if possible. those are just the sample HashIntSet and HashMain (don't have to be the same but follow the Q requirement. thanks HashIntSet.java public class HashIntSet { private static final double MAX_LOAD_FACTOR = 0.75; private HashEntry[] elementData; private int size; // Constructs an empty set. public HashIntSet() { elementData = new HashEntry[10]; size = 0; } // Adds the given element to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT