ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCOMP2117Open Addressing Chaini…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    COMP2117

    Data Structures

    Progress0 / 37 done
    Topics37
    1Abstract Data Types2Complexity Analysis3Big Oh Notation4Stacks (Linked Lists and Array Implementations)5Recursion and analyzing recursive algorithms6Divide and Conquer Algorithms7Sorting Algorithms8Selection Sort9Insertion Sort10Merge Sort11Quick Sort12Bubble Sort13Heap Sort14Shell Sort15Radix Sort16Bucket Sort17Queue18Dequeuer19Priority Queues (linked and array implementations of queues)20Linked List and Its Various Types21Sorted Linked List22Searching an Unsorted Array23Binary Search for Sorted Arrays24Hashing and Indexing25Open Addressing and Chaining26Trees and Tree Traversals27Binary Search Trees28Heaps29M-Way Trees30Balanced Trees31Graphs32Breadth-First Traversal33Depth-First Traversal34Topological Order35Shortest Path36Adjacency Matrix and Adjacency List Implementations37Memory Management and Garbage Collection
    6 min read
    Topic 25 of 37
    Topic Study Note Illustration
    25

    Open Addressing and Chaining

    Open Addressing and Chaining are two popular techniques for handling collisions in hash tables. Collisions occur when two or more keys produce the same hash value, leading...

    Open Addressing and Chaining are two popular techniques for handling collisions in hash tables. Collisions occur when two or more keys produce the same hash value, leading them to the same location in the hash table.

    Here’s a detailed look at each method:


    Open Addressing

    Open Addressing resolves collisions by finding another open slot within the hash table itself. When a collision happens, the algorithm searches for an empty slot (or address) according to a specific probing method. This means that each element stays within the table array, without using additional data structures like linked lists.

    Types of Probing Techniques in Open Addressing

    1. Linear Probing:

      • When a collision occurs, it moves to the next slot in the array (index + 1) until it finds an empty slot.
      • If the end of the table is reached, it wraps around to the beginning.
      • Drawback: Linear probing can cause primary clustering, where clusters of occupied slots form, leading to slower search times.

      Example: index = (hash + i) % tableSize

    2. Quadratic Probing:

      • Instead of moving linearly, it moves in quadratic steps to find an open slot. For example, it checks the slots at (hash + 1^2), (hash + 2^2), etc.
      • This reduces primary clustering but can lead to secondary clustering, where keys with the same hash value probe the same sequence of positions.

      Example: index = (hash + i^2) % tableSize

    3. Double Hashing:

      • Double hashing uses a second hash function to determine the step size for probing, which minimizes clustering.
      • This is one of the most effective probing techniques for avoiding collisions.

      Example: index = (hash1(key) + i * hash2(key)) % tableSize

    C++ Example of Open Addressing (Linear Probing)

    #include <iostream>
    #include <vector>
    using namespace std;
    
    class HashTable {
        vector<int> table;
        int tableSize;
    
    public:
        HashTable(int size) : table(size, -1), tableSize(size) {}  // Initialize table with -1
    
        int hashFunction(int key) {
            return key % tableSize;
        }
    
        void insert(int key) {
            int index = hashFunction(key);
            int i = 0;
    
            // Linear probing
            while (table[(index + i) % tableSize] != -1) {
                i++;
            }
    
            table[(index + i) % tableSize] = key;
            cout << "Inserted " << key << " at index " << (index + i) % tableSize << endl;
        }
    
        void display() {
            for (int i = 0; i < tableSize; i++) {
                cout << i << ": " << table[i] << endl;
            }
        }
    };
    
    int main() {
        HashTable ht(7);
        ht.insert(10);
        ht.insert(20);
        ht.insert(15);
        ht.insert(7);
        ht.display();
        return 0;
    }
    

    Advantages and Disadvantages of Open Addressing

    • Advantages:
      • No extra memory is needed outside the hash table.
      • Useful in memory-constrained environments.
    • Disadvantages:
      • Primary and secondary clustering issues can degrade performance.
      • Table can fill up faster, requiring rehashing to increase capacity.

    Chaining

    Chaining resolves collisions by storing all elements that hash to the same index in a linked list (or any other data structure like a dynamic array) at that index. When a collision occurs, the new element is added to the linked list at the hashed index, allowing multiple elements to exist at the same index.

    How Chaining Works

    1. Insert: Calculate the index using the hash function. If there’s already an element at this index, append the new element to the linked list at that index.
    2. Search: Calculate the index and search through the linked list at that index to find the desired key.
    3. Delete: Calculate the index and delete the element from the linked list at that index if it exists.

    C++ Example of Hashing with Chaining

    #include <iostream>
    #include <list>
    #include <vector>
    using namespace std;
    
    class HashTable {
        vector<list<int>> table;  // Each index stores a linked list
        int tableSize;
    
    public:
        HashTable(int size) : table(size), tableSize(size) {}
    
        int hashFunction(int key) {
            return key % tableSize;
        }
    
        void insert(int key) {
            int index = hashFunction(key);
            table[index].push_back(key);
            cout << "Inserted " << key << " at index " << index << endl;
        }
    
        void display() {
            for (int i = 0; i < tableSize; i++) {
                cout << i << ": ";
                for (int key : table[i]) {
                    cout << key << " -> ";
                }
                cout << "nullptr" << endl;
            }
        }
    };
    
    int main() {
        HashTable ht(7);
        ht.insert(10);
        ht.insert(20);
        ht.insert(15);
        ht.insert(7);
        ht.display();
        return 0;
    }
    

    Advantages and Disadvantages of Chaining

    • Advantages:
      • Avoids clustering issues.
      • Allows a dynamic number of elements (linked lists can grow as needed).
    • Disadvantages:
      • Requires additional memory for linked list pointers.
      • Performance may degrade if too many elements are stored in a single linked list, leading to O(n)O(n)O(n) search time in the worst case.

    Comparison of Open Addressing and Chaining

    Feature Open Addressing Chaining
    Structure Stores all elements within the array Uses linked lists at each index
    Memory Usage Only the hash table size is used Additional memory needed for linked lists
    Collision Resolution Finds alternative slots using probing Stores collided elements in a linked list
    Clustering Subject to clustering No clustering, as lists are separate
    Performance Can degrade with clustering Performance stable with well-sized lists
    Table Fullness Degrades as table nears capacity Can handle more elements than table size

    When to Use Each

    • Open Addressing is suitable when memory is limited, and the load factor (number of elements compared to the table size) is kept below 0.7.
    • Chaining is more flexible, especially when frequent insertions are expected, and load factor could be higher than 1 (number of elements exceeds table size).

    In summary:

    • Use open addressing when memory is constrained and the table load is low.
    • Use chaining for dynamic storage and to avoid clustering issues, especially in environments where extra memory for linked lists is available.
    ← Previous topic 24
    Hashing and Indexing
    Next topic 26 →
    Trees and Tree Traversals

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.0kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Data Structures