Hashing
Hashing
Hashing Techniques
SUPERVISOR: Eng/ Noor El-Deen Magdy
Faculty of Engineering,
𝟐𝒏𝒅 Year Computer and Systems Department
Intro to Hashing:
Hashing is a data processing technique that maps data elements
(keys) to a specific location in memory, known as a hash table, using a
hash function. This technique provides efficient access to data with
average time complexity of O(1) for insertion, deletion, and search
operations.
Key Components:
1-Hash Function: Maps keys to indices in the hash table.
Example: h(k)=k%m, where m is the table size.
2-Hash Table: An array-like data structure to store key-value pairs.
3-Collision Handling: When multiple keys hash to the same index,
collisions occur. Collision resolution is necessary for efficient
operation.
Collision Resolution Techniques:
1-Separate Chaining:
o Each hash table index stores a linked list of key-value pairs.
o Example: Index 2 may hold a linked list if keys 12 and 22 collide.
2-Open Addressing:
Probes for the next available slot in the hash table. Types include:
o Linear Probing: Check the next slot sequentially until an empty
slot is found. ex: h(k,i)=(h(k)+i)%m.
o Quadratic Probing: Check slots using quadratic increments.
Example: h(k,i)=(h(k)+i^2)%m.
o Double Hashing: Use a secondary hash function to find slots.
Example: h(k,i)=(h1(k)+i×h2(k))%
3-Perfect Hashing:
Design a collision-free hash function for a fixed dataset.
*Example with Implementation:
Linked List:
#include <iostream>
#include <list>
using namespace std;
class HashTable {
int size;
list<int>* table;
public:
HashTable(int size) {
this->size = size;
table = new list<int>[size];
}
void display() {
for (int i = 0; i < size; i++) {
cout << i << ": ";
for (int key : table[i]) {
cout << key << " -> ";
}
cout << "null" << endl;
}
}
};