Hash Table with Chaining


What is Hashing?

Hashing is a technique to convert data (like a string, number, etc.) into a small fixed-size value called a hash code using a mathematical function called a hash function.

✅ Purpose:

  • Fast access

  • Fast insertion, deletion, and search


What is a Hash Table?

A Hash Table is a data structure that stores data in an array-like format using the hash code as an index.

  • Key → Hash Function → Index → Store value at that index

  • If two keys generate the same index, we resolve it using methods like chaining (linked list at that index) or open addressing (find next empty spot).


 How to Implement a Simple Hash Table?

Steps:

  1. Choose a hash function (e.g., key % size).

  2. Create an array of fixed size.

  3. Insert, search, and delete elements based on the hash value.


Key Points:

  • Hash Function: Should distribute keys evenly.

  • Collisions: Resolved by chaining (linked list) or open addressing (probing).

  • Time Complexity:

    • Best case: O(1) for insert/search/delete

    • Worst case (many collisions): O(n)


Algorithms for Hash Table


1. Hash Table with Chaining (using Linked List)

Idea:
Each index of the table stores a linked list to handle collisions (multiple keys at same index).


🔹 Insertion Algorithm (Chaining)

1. Compute index = hash(key)
2. Create a new node with (key, value) 3. Insert the new node at the beginning of the linked list at hashTable[index]

🔹 Search Algorithm (Chaining)


1. Compute index = hash(key) 2. Traverse the linked list at hashTable[index] 3. If node.key == key, return node.value 4. If end of list is reached, return NOT FOUND

🔹 Deletion Algorithm (Chaining)


1. Compute index = hash(key) 2. Traverse the linked list at hashTable[index] 3. If node.key == key: a. Adjust previous node's next pointer b. Free the current node 4. If end of list is reached without finding, print "Key not found"

C Program Hash Table with Chaining

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 11

// Node for chaining
struct Node {
    int key;
    int value;
    struct Node* next;
};

struct Node* hashTable[SIZE];

// Hash function
int hashFunction(int key) {
    return key % SIZE;
}

// Insert key-value pair
void insert(int key, int value) {
    int index = hashFunction(key);
    
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->key = key;
    newNode->value = value;
    newNode->next = hashTable[index];
    hashTable[index] = newNode;
}

// Search for a value by key
int search(int key) {
    int index = hashFunction(key);
    struct Node* temp = hashTable[index];
    
    while (temp != NULL) {
        if (temp->key == key)
            return temp->value;
        temp = temp->next;
    }
    return -1; // not found
}

// Delete a key-value pair
void delete(int key) {
    int index = hashFunction(key);
    struct Node* temp = hashTable[index];
    struct Node* prev = NULL;
    
    while (temp != NULL) {
        if (temp->key == key) {
            if (prev == NULL)
                hashTable[index] = temp->next;
            else
                prev->next = temp->next;
            
            free(temp);
            printf("Deleted key %d\n", key);
            return;
        }
        prev = temp;
        temp = temp->next;
    }
    printf("Key %d not found!\n", key);
}

// Display hash table
void display() {
    for (int i = 0; i < SIZE; i++) {
        printf("[%d]: ", i);
        struct Node* temp = hashTable[i];
        while (temp != NULL) {
            printf("(%d,%d) -> ", temp->key, temp->value);
            temp = temp->next;
        }
        printf("NULL\n");
    }
}

int main() {
    int choice, key, value;
    
    while (1) {
        printf("\n1. Insert\n2. Search\n3. Delete\n4. Display\n5. Exit\nEnter your choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("Enter key and value: ");
                scanf("%d%d", &key, &value);
                insert(key, value);
                break;
            case 2:
                printf("Enter key to search: ");
                scanf("%d", &key);
                value = search(key);
                if (value != -1)
                    printf("Found: Value = %d\n", value);
                else
                    printf("Key not found!\n");
                break;
            case 3:
                printf("Enter key to delete: ");
                scanf("%d", &key);
                delete(key);
                break;
            case 4:
                display();
                break;
            case 5:
                exit(0);
            default:
                printf("Invalid choice!\n");
        }
    }
    
    return 0;
}

Comments

Popular posts from this blog

Data Structures Lab PCCSL307 KTU 2024 Scheme - Dr Binu V P

Sparse Matrix - Transpose and Addition

Polynomial Addition using Arrays