Assignment No 1 DSA
Assignment No 1 DSA
1
Title: Implementation of hash Table.
Program:
#include<iostream>
#include<cstring>
using namespace std;
struct hashTable{
string key;
int64_t value;
bool isEmpty=true;
hashTable *next;
};
class Contacts{
int num; //number of entries
hashTable *phoneBook;
public:
Contacts():phoneBook(NULL){
}
void ins(){
int index;
int64_t phoneNumber;
string name;
cout<<"enter number of entries: ";
cin>>num;
phoneBook=new hashTable[num];
cout<<"Enter name and phone number respectively:"<<endl;
for(int i=0;i<num;i++){
cin>>name>>phoneNumber;
index=hashing(name,num);
if(phoneBook[index].isEmpty){ //if the slot is empty(no collision)...
phoneBook[index].key=name;
phoneBook[index].value=phoneNumber;
phoneBook[index].isEmpty=false; //it is now filled...
phoneBook[index].next=NULL;
}
else{ //in case of collision...
hashTable *temp=&(phoneBook[index]);
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=new hashTable;
temp->next->key=name;
temp->next->value=phoneNumber;
temp->next->isEmpty=false;
temp->next->next=NULL;
}
}
}
int hashing(string name,int n){
int len,sum=0;
//converting string into char array...
len=name.length();
char temp[len+1];
strcpy(temp,name.c_str());
//calculating hash value...
for(int i=0;i<len;i++){
sum=sum+temp[i];
}
return (sum%n);
}
void searchContact(string name){
int check;
check=hashing(name,num);
Output:
PS C:\Users\Tejas> cd "C:\Users\Tejas\AppData\Local\Temp\" ; if ($?) { g++
tempCodeRunnerFile.cpp -o tempCodeRunnerFile } ; if ($?) { .\tempCodeRunnerFile }
enter number of entries: 4
Enter name and phone number respectively:
Tejas 9730775000
Nehal 9420880000
Viraj 9074570000
Keshav 9657540000
Enter number of names you want to search: 2
Enter names:
Nehal
Name: Nehal
Phone number: 9420880000
Tejas
Name: Tejas
Phone number: 9730775000