Implement Phone Directory using Hashing
Last Updated :
15 Feb, 2024
Hashing is a technique that uses fewer key comparisons and searches the element in O(n) time in the worst case and in O(1) time in the average case.
- The task is to implement all functions of phone directory:
- create_record
- display_record
- delete_record
- search_record
- update_record
Following data will be taken from the client:
ID, Name, Telephone number
Approach:
We are creating a hash table, and inserting records. For deleting, searching, or updating an entity, the client ID is asked and on the basis of equality operator, details are displayed or processed. If the record is not found, then an appropriate message is displayed. Collision is the major problem in the hashing technique. In
open addressing (closed hashing), all collisions are resolved in the prime area i.e., the area that contains all of the home addresses. When a collision occurs, the prime area addresses are searched for an open or unoccupied element using linear probing. Steps for inserting entities in a hash table:
1
. If the location is empty, directly insert the entity.
2
. If mapped location is occupied then keep probing until an empty slot is found. Once an empty slot is found, insert the entity.
- Create Record: This method takes details from the user like ID, Name and Telephone number and create new record in the hashtable.
- Display Record: This function is created to display all the record of the diary.
- Delete Record: This method takes the key of the record to be deleted. Then, it searches in hash table if record id matches with the key. Then, that record is deleted.
- Search Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key it displays the record detail.
- Update Record: This method takes the key of the record to be searched. Then, it traverses the hash table, if record id matches with the key then it displays the record detail.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
// Class to store contact
// details
class node {
string name;
long int tel;
int id;
public:
node()
{
tel = 0;
id = 0;
}
friend class hashing;
};
class hashing {
// Maximum size of
// directory is 100
node data[100];
string n;
long int t;
int i, index;
public:
hashing()
{
i = 0;
t = 0;
}
// This method takes details
// from the user like ID,
// Name and Telephone number
// and create new record in
// the hashtable.
void create_record(int size)
{
// Enter ID
i = 4;
// Enter Name
n = "XYZ Gupta";
// Enter telephone number
t = 23451234;
cout << "\nEnter id :";
cout << " \t\t\t"
<< i;
cout << "\nEnter name :";
cout << " \t\t\t " << n;
cout
<< "\nEnter telephone";
cout << " number :\t"
<< t;
index = i % size;
// Inserting record using linear
// probing in case of collision
for (int j = 0; j < size; j++) {
if (data[index].id == 0) {
data[index].id = i;
data[index].name = n;
data[index].tel = t;
break;
}
else
index
= (index + 1) % size;
}
}
// This method takes the key of
// the record to be searched.
// Then, it traverses the hash
// table, if record id matches
// with the key it displays the
// record detail.
void search_record(int size)
{
int index1, key, flag = 0;
key = 4;
cout << "\nEnter record";
cout << " id to search : "
<< key;
index1 = key % size;
// Traversing the directory
// linearly inorder to search
// record detail
for (int a = 0; a < size; a++) {
if (data[index1].id == key) {
flag = 1;
cout << "\nRecord found:";
cout << "\n\tID ";
cout << "\tNAME ";
cout << "\t\tTELEPHONE ";
cout << "\n\t"
<< data[index1].id
<< " \t"
<< data[index1].name
<< " \t"
<< data[index1].tel;
break;
}
else
index1
= (index1 + 1) % size;
}
if (flag == 0)
cout << "\nRecord";
cout << " not found";
}
// This method takes the key
// of the record to be deleted.
// Then, it searches in hash
// table if record id matches
// with the key. Then, that
// record is deleted.
void delete_record(int size)
{
int index1, key, flag = 0;
key = 4;
cout << "\nEnter record";
cout << " id to delete : "
<< key << "\n ";
index1 = key % size;
// Traversing the directory
// linearly inorder to delete
// the record detail
for (int a = 0; a < size; a++) {
if (data[index1].id
== key) {
flag = 1;
data[index1].id = 0;
data[index1].name = " ";
data[index1].tel = 0;
cout << "\nRecord";
cout << " deleted";
cout << " successfully";
break;
}
else
index1
= (index1 + 1) % size;
}
if (flag == 0)
cout << "\nRecord";
cout << " not found";
}
// This method takes the key
// of the record to be searched.
// Then, it traverses the hash table,
// if record id matches with the
// key then it displays the record
// detail.
void update_record(int size)
{
int index1, key, flag = 0;
key = 4;
cout << "\nEnter record";
cout << " id to update : "
<< key;
index1 = key % size;
// Traversing the directory
// linearly inorder to search
// record detail
for (int a = 0; a < size; a++) {
if (data[index1].id
== key) {
flag = 1;
break;
}
else
index1
= (index1 + 1) % size;
}
// If the record is found
// the details are updated
if (flag == 1) {
n = "XYZ Agarwal";
t = 23413421;
data[index1].name = n;
data[index1].tel = t;
cout << "\nEnter";
cout << " name: \t\t\t"
<< n;
cout << "\nEnter";
cout << " telephone number: \t"
<< t;
cout << "\nDetails updated: ";
cout << "\n\tID \tNAME";
cout << " \t\tTELEPHONE ";
cout << "\n\t"
<< data[index1].id
<< " \t"
<< data[index1].name
<< " \t"
<< data[index1].tel;
}
}
// This function is created to
// display all the record of
// the diary.
void display_record(int size)
{
cout << "\n\tID \tNAME";
cout << " \t\tTELEPHONE ";
// Displaying the details of
// all records of the directory.
for (int a = 0; a < size; a++) {
if (data[a].id != 0) {
cout << "\n\t"
<< data[a].id
<< " \t"
<< data[a].name
<< " \t"
<< data[a].tel;
}
}
}
};
// Driver code
int main()
{
// size of directory
int size;
// creating object of hashing
// class
hashing s;
size = 20;
// Creating a record in
// directory
cout << "\n1.CREATE record ";
s.create_record(size);
// Display available
// record details
cout << "\n\n\n\n2.DISPLAY";
cout << " record ";
s.display_record(size);
// Searching a record detail
// in the directory
cout << "\n\n\n\n3.SEARCH";
cout << " record";
s.search_record(size);
// Updating the existing
// details of a record
cout << "\n\n\n\n4.UPDATE";
cout << " record ";
s.update_record(size);
// Removing specified
// existing record
// from dictionary
cout << "\n\n\n\n5.DELETE";
cout << " record ";
s.delete_record(size);
return 0;
}
Java
import java.util.Arrays;
// Class to store contact details
class Node {
String name;
long tel;
int id;
Node() {
tel = 0;
id = 0;
}
}
public class Hashing {
// Maximum size of directory is 100
Node[] data = new Node[100];
String n;
long t;
int i, index;
Hashing() {
i = 0;
t = 0;
}
// This method creates a new record in the hashtable.
void createRecord(int size) {
i = 4;
n = "XYZ Gupta";
t = 23451234;
System.out.println("\nEnter id : " + i);
System.out.println("Enter name : " + n);
System.out.println("Enter telephone number : " + t);
index = i % size;
for (int j = 0; j < size; j++) {
if (data[index] == null) {
data[index] = new Node();
data[index].id = i;
data[index].name = n;
data[index].tel = t;
break;
} else {
index = (index + 1) % size;
}
}
}
// This method searches for a record using the ID.
void searchRecord(int size) {
int index1, key;
key = 4;
System.out.println("\nEnter record id to search : " + key);
index1 = key % size;
for (int a = 0; a < size; a++) {
if (data[index1] != null && data[index1].id == key) {
System.out.println("\nRecord found:");
System.out.println("\tID \tNAME \tTELEPHONE");
System.out.println("\t" + data[index1].id + " \t" +
data[index1].name + " \t" + data[index1].tel);
return;
} else {
index1 = (index1 + 1) % size;
}
}
System.out.println("\nRecord not found");
}
// This method deletes a record using the ID.
void deleteRecord(int size) {
int index1, key;
key = 4;
System.out.println("\nEnter record id to delete : " + key);
index1 = key % size;
for (int a = 0; a < size; a++) {
if (data[index1] != null && data[index1].id == key) {
data[index1] = null;
System.out.println("\nRecord deleted successfully");
return;
} else {
index1 = (index1 + 1) % size;
}
}
System.out.println("\nRecord not found");
}
// This method updates an existing record using the ID.
void updateRecord(int size) {
int index1, key;
key = 4;
System.out.println("\nEnter record id to update : " + key);
index1 = key % size;
for (int a = 0; a < size; a++) {
if (data[index1] != null && data[index1].id == key) {
data[index1].name = "XYZ Agarwal";
data[index1].tel = 23413421;
System.out.println("\nDetails updated:");
System.out.println("\tID \tNAME \tTELEPHONE");
System.out.println("\t" + data[index1].id + " \t" +
data[index1].name + " \t" + data[index1].tel);
return;
} else {
index1 = (index1 + 1) % size;
}
}
}
// This method displays all records in the directory.
void displayRecord(int size) {
System.out.println("\nID \tNAME \tTELEPHONE");
for (int a = 0; a < size; a++) {
if (data[a] != null) {
System.out.println("\t" + data[a].id + " \t" +
data[a].name + " \t" + data[a].tel);
}
}
}
// Driver code
public static void main(String[] args) {
int size = 20;
Hashing s = new Hashing();
System.out.println("\n1.CREATE record ");
s.createRecord(size);
System.out.println("\n2.DISPLAY record ");
s.displayRecord(size);
System.out.println("\n3.SEARCH record ");
s.searchRecord(size);
System.out.println("\n4.UPDATE record ");
s.updateRecord(size);
System.out.println("\n5.DELETE record ");
s.deleteRecord(size);
}
}
// This code is contributed by shivamgupta0987654321
Python3
class Node:
def __init__(self):
self.name = ""
self.tel = 0
self.id = 0
class Hashing:
def __init__(self):
self.data = [Node() for _ in range(100)]
def create_record(self, size):
i = 4
n = "XYZ Gupta"
t = 23451234
print(f"\nEnter id : {i}")
print(f"\nEnter name : {n}")
print(f"\nEnter telephone number : {t}")
index = i % size
while True:
if self.data[index].id == 0:
self.data[index].id = i
self.data[index].name = n
self.data[index].tel = t
break
else:
index = (index + 1) % size
def search_record(self, size):
key = 4
print(f"\nEnter record id to search : {key}")
index = key % size
found = False
for _ in range(size):
if self.data[index].id == key:
found = True
print(f"\nRecord found:")
print(f"ID\tNAME\t\tTELEPHONE")
print(f"{self.data[index].id}\t{self.data[index].name}\t{self.data[index].tel}")
break
else:
index = (index + 1) % size
if not found:
print("\nRecord not found")
def delete_record(self, size):
key = 4
print(f"\nEnter record id to delete : {key}")
index = key % size
found = False
for _ in range(size):
if self.data[index].id == key:
found = True
self.data[index].id = 0
self.data[index].name = ""
self.data[index].tel = 0
print("\nRecord deleted successfully")
break
else:
index = (index + 1) % size
if not found:
print("\nRecord not found")
def update_record(self, size):
key = 4
print(f"\nEnter record id to update : {key}")
index = key % size
found = False
for _ in range(size):
if self.data[index].id == key:
found = True
self.data[index].name = "XYZ Agarwal"
self.data[index].tel = 23413421
print(f"\nEnter name: {self.data[index].name}")
print(f"Enter telephone number: {self.data[index].tel}")
print("\nDetails updated:")
print(f"ID\tNAME\t\tTELEPHONE")
print(f"{self.data[index].id}\t{self.data[index].name}\t{self.data[index].tel}")
break
else:
index = (index + 1) % size
if not found:
print("\nRecord not found")
def display_record(self, size):
print(f"ID\tNAME\t\tTELEPHONE")
for node in self.data:
if node.id != 0:
print(f"{node.id}\t{node.name}\t{node.tel}")
if __name__ == "__main__":
size = 20
s = Hashing()
print("\n1.CREATE record ")
s.create_record(size)
print("\n\n2.DISPLAY record ")
s.display_record(size)
print("\n\n3.SEARCH record")
s.search_record(size)
print("\n\n4.UPDATE record ")
s.update_record(size)
print("\n\n5.DELETE record ")
s.delete_record(size)
# This code is contributed by AKSHITAGUPRZJ3
C#
using System;
// Class to store contact details
class Node
{
public string Name;
public long Telephone;
public int Id;
public Node()
{
Telephone = 0;
Id = 0;
}
}
// Class for hash operations
class Hashing
{
// Maximum size of directory is 100
Node[] data = new Node[100];
string n;
long t;
int i, index;
public Hashing()
{
i = 0;
t = 0;
}
// Method to create a new record in the hashtable
public void CreateRecord(int size)
{
i = 4;
n = "XYZ Gupta";
t = 23451234;
Console.WriteLine("\nEnter id : " + i);
Console.WriteLine("Enter name : " + n);
Console.WriteLine("Enter telephone number : " + t);
index = i % size;
// Inserting record using linear probing in case of collision
for (int j = 0; j < size; j++)
{
if (data[index] == null)
{
data[index] = new Node { Id = i, Name = n, Telephone = t };
break;
}
else
index = (index + 1) % size;
}
}
// Method to search for a record in the hashtable
public void SearchRecord(int size)
{
int index1, key, flag = 0;
key = 4;
Console.WriteLine("\nEnter record id to search : " + key);
index1 = key % size;
// Traversing the directory linearly to search record detail
for (int a = 0; a < size; a++)
{
if (data[index1]?.Id == key)
{
flag = 1;
Console.WriteLine("\nRecord found:");
Console.WriteLine("\tID \tNAME \t\tTELEPHONE ");
Console.WriteLine("\t" + data[index1].Id + " \t" + data[index1].Name + " \t" + data[index1].Telephone);
break;
}
else
index1 = (index1 + 1) % size;
}
if (flag == 0)
Console.WriteLine("\nRecord not found");
}
// Method to delete a record from the hashtable
public void DeleteRecord(int size)
{
int index1, key, flag = 0;
key = 4;
Console.WriteLine("\nEnter record id to delete : " + key);
index1 = key % size;
// Traversing the directory linearly to delete the record detail
for (int a = 0; a < size; a++)
{
if (data[index1]?.Id == key)
{
flag = 1;
data[index1] = null;
Console.WriteLine("\nRecord deleted successfully");
break;
}
else
index1 = (index1 + 1) % size;
}
if (flag == 0)
Console.WriteLine("\nRecord not found");
}
// Method to update a record in the hashtable
public void UpdateRecord(int size)
{
int index1, key, flag = 0;
key = 4;
Console.WriteLine("\nEnter record id to update : " + key);
index1 = key % size;
// Traversing the directory linearly to search record detail
for (int a = 0; a < size; a++)
{
if (data[index1]?.Id == key)
{
flag = 1;
break;
}
else
index1 = (index1 + 1) % size;
}
// If the record is found, the details are updated
if (flag == 1)
{
n = "XYZ Agarwal";
t = 23413421;
data[index1].Name = n;
data[index1].Telephone = t;
Console.WriteLine("\nEnter name: \t\t\t" + n);
Console.WriteLine("Enter telephone number: \t" + t);
Console.WriteLine("Details updated: ");
Console.WriteLine("\n\tID \tNAME \t\tTELEPHONE ");
Console.WriteLine("\t" + data[index1].Id + " \t" + data[index1].Name + " \t" + data[index1].Telephone);
}
}
// Method to display all records in the hashtable
public void DisplayRecord(int size)
{
Console.WriteLine("\n\tID \tNAME \t\tTELEPHONE ");
// Displaying the details of all records in the directory
for (int a = 0; a < size; a++)
{
if (data[a] != null)
{
Console.WriteLine("\t" + data[a].Id + " \t" + data[a].Name + " \t" + data[a].Telephone);
}
}
}
}
// Driver code
class Program
{
static void Main()
{
// Size of directory
int size;
// Creating object of Hashing class
Hashing s = new Hashing();
size = 20;
// Creating a record in directory
Console.WriteLine("\n1.CREATE record ");
s.CreateRecord(size);
// Display available record details
Console.WriteLine("\n\n\n\n2.DISPLAY record ");
s.DisplayRecord(size);
// Searching a record detail in the directory
Console.WriteLine("\n\n\n\n3.SEARCH record");
s.SearchRecord(size);
// Updating the existing details of a record
Console.WriteLine("\n\n\n\n4.UPDATE record ");
s.UpdateRecord(size);
// Removing specified existing record from dictionary
Console.WriteLine("\n\n\n\n5.DELETE record ");
s.DeleteRecord(size);
}
}
JavaScript
// Class to store contact details
class Node {
constructor() {
this.name = '';
this.tel = 0;
this.id = 0;
}
}
class Hashing {
constructor() {
this.data = new Array(100);
this.n = '';
this.t = 0;
this.i = 0;
this.index = 0;
}
// This method creates a new record in the hashtable.
createRecord(size) {
this.i = 4;
this.n = 'XYZ Gupta';
this.t = 23451234;
console.log('\nEnter id : ' + this.i);
console.log('Enter name : ' + this.n);
console.log('Enter telephone number : ' + this.t);
this.index = this.i % size;
for (let j = 0; j < size; j++) {
if (this.data[this.index] === undefined) {
this.data[this.index] = new Node();
this.data[this.index].id = this.i;
this.data[this.index].name = this.n;
this.data[this.index].tel = this.t;
break;
} else {
this.index = (this.index + 1) % size;
}
}
}
// This method searches for a record using the ID.
searchRecord(size) {
let index1, key;
key = 4;
console.log('\nEnter record id to search : ' + key);
index1 = key % size;
for (let a = 0; a < size; a++) {
if (this.data[index1] !== undefined && this.data[index1].id === key) {
console.log('\nRecord found:');
console.log('\tID \tNAME \tTELEPHONE');
console.log('\t' + this.data[index1].id + ' \t' +
this.data[index1].name + ' \t' + this.data[index1].tel);
return;
} else {
index1 = (index1 + 1) % size;
}
}
console.log('\nRecord not found');
}
// This method deletes a record using the ID.
deleteRecord(size) {
let index1, key;
key = 4;
console.log('\nEnter record id to delete : ' + key);
index1 = key % size;
for (let a = 0; a < size; a++) {
if (this.data[index1] !== undefined && this.data[index1].id === key) {
this.data[index1] = undefined;
console.log('\nRecord deleted successfully');
return;
} else {
index1 = (index1 + 1) % size;
}
}
console.log('\nRecord not found');
}
// This method updates an existing record using the ID.
updateRecord(size) {
let index1, key;
key = 4;
console.log('\nEnter record id to update : ' + key);
index1 = key % size;
for (let a = 0; a < size; a++) {
if (this.data[index1] !== undefined && this.data[index1].id === key) {
this.data[index1].name = 'XYZ Agarwal';
this.data[index1].tel = 23413421;
console.log('\nDetails updated:');
console.log('\tID \tNAME \tTELEPHONE');
console.log('\t' + this.data[index1].id + ' \t' +
this.data[index1].name + ' \t' + this.data[index1].tel);
return;
} else {
index1 = (index1 + 1) % size;
}
}
}
// This method displays all records in the directory.
displayRecord(size) {
console.log('\nID \tNAME \tTELEPHONE');
for (let a = 0; a < size; a++) {
if (this.data[a] !== undefined) {
console.log('\t' + this.data[a].id + ' \t' +
this.data[a].name + ' \t' + this.data[a].tel);
}
}
}
}
// Driver code
function main() {
const size = 20;
const s = new Hashing();
console.log('\n1.CREATE record ');
s.createRecord(size);
console.log('\n2.DISPLAY record ');
s.displayRecord(size);
console.log('\n3.SEARCH record ');
s.searchRecord(size);
console.log('\n4.UPDATE record ');
s.updateRecord(size);
console.log('\n5.DELETE record ');
s.deleteRecord(size);
}
main();
Output:
Similar Reads
How to Get Current Directory in C++ The current working directory, also known as the present working directory, is the location on the file system where the executing program is located and operates from. When working with files and directories in C++, it is important to determine the current working directory to find the resource fil
2 min read
How to Check a File or Directory Exists in C++? Checking the presence of a directory or a file is one of the most common operations performed by a file system in an Operating System. Most programming languages offer some level of file system accessibility in form of library functions. In this article, you will learn how to test a file or director
4 min read
C++ Program to Get the List of Files in a Directory Getting the list of files in a directory is one of the most common operations performed by the Filesystem of an OS. The file explorer application in most operating systems performs the same operation in the background. In this article, you will learn how to get the list of files in a directory using
4 min read
How to Get the MD5 Hash of a File in C++? In cryptography, we use the MD5 (Message Digest Algorithm 5) hash function for creating a 128-bit hash value which is represented as a 32-character hexadecimal number. However, this algorithm is not very secure cryptographically but can be used for file verifications, checksums, and ensuring data in
5 min read
Create Directory or Folder with C/C++ Program Problem: Write a C/C++ program to create a folder in a specific directory path. This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty director
2 min read