From 7747d3a6c38bb45fec5cd89789b4f1e56bb83321 Mon Sep 17 00:00:00 2001 From: vasutomar Date: Tue, 17 Apr 2018 14:12:30 +0530 Subject: [PATCH 1/3] Hashing implementation with chaining collision resolution --- Hashing/Chaining.cpp | 132 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 Hashing/Chaining.cpp diff --git a/Hashing/Chaining.cpp b/Hashing/Chaining.cpp new file mode 100644 index 000000000..6242312cf --- /dev/null +++ b/Hashing/Chaining.cpp @@ -0,0 +1,132 @@ +#include +#include +using namespace std; +struct node{ + int data; + struct node *next; +} *head[100],*curr; + +void init(){ + for(int i=0;i<100;i++) + head[i]=NULL; +} + +void add(int x,int h){ + struct node *temp = new node; + temp->data = x; + temp->next = NULL; + if(head[h]==NULL){ + head[h] = temp; + curr=head[h]; + } + else{ + curr=head[h]; + while(curr->next!=NULL) + curr=curr->next; + curr->next = temp; + } +} + +void display(int mod){ + struct node *temp; + int i; + for(i=0;inext; + } + cout<data; + cout<data==x) + break; + else if(temp->next==NULL) + break; + temp=temp->next; + } + if(temp->next!=NULL) + cout<<"Element found"; + else{ + if(temp->data==x) + cout<<"Element found"; + else + cout<<"Element not found"; + } +} + +int main(void){ + init(); + int c,x,mod; + cout<<"Enter the size of Hash Table. = "; + cin>>mod; + while(1){ + cout<>c; + switch(c){ + case 1:{ + cout<<"Enter element to add = "; + cin>>x; + int h = hash(x,mod); + if(h<0) + h=fabs(h); + add(x,h); + break; + } + case 2:{ + cout<<"Enter element to search = "; + cin>>x; + int h=hash(x,mod); + find(x,h); + break; + } + case 3:{ + cout<<"Enter element to generate hash = "; + cin>>x; + cout<<"Hash of "<next; } @@ -47,39 +49,35 @@ void display(int mod){ } } -int hash(int x,int mod){ +int hash(int x,int mod) { return x%mod; } -void find(int x,int h){ - struct node *temp =head[h]; - if(head[h]==NULL){ +void find(int x,int h) { + struct Node *temp =head[h]; + if(!head[h]) { cout<<"Element not found"; return; } - while(1){ - if(temp->data==x) - break; - else if(temp->next==NULL) - break; + while(temp->data !=x && temp->next) temp=temp->next; - } - if(temp->next!=NULL) + if(temp->next) cout<<"Element found"; else{ - if(temp->data==x) + if(temp->data == x) cout<<"Element found"; else - cout<<"Element not found"; + cout<< "Element not found"; } } -int main(void){ +int main(void) { init(); - int c,x,mod; + int c,x,mod,h; cout<<"Enter the size of Hash Table. = "; cin>>mod; - while(1){ + bool loop = true; + while(loop) { cout<>c; - switch(c){ - case 1:{ + switch(c) { + case 1: cout<<"Enter element to add = "; cin>>x; - int h = hash(x,mod); - if(h<0) - h=fabs(h); + h = hash(x,mod); + h = fabs(h); add(x,h); break; - } - case 2:{ + case 2: cout<<"Enter element to search = "; cin>>x; - int h=hash(x,mod); + h = hash(x,mod); find(x,h); break; - } - case 3:{ + case 3: cout<<"Enter element to generate hash = "; cin>>x; cout<<"Hash of "<