-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashing.cpp
138 lines (116 loc) · 1.99 KB
/
hashing.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 10
struct node
{
int data;
struct node *next;
};
struct node *start[size]={NULL};
int table[size]={0};int hash,i;
void linear_probing(int hash,int elem)
{
int flag=0;
while(flag!=1)
{
if(hash==size-1)
hash=-1;
hash++;
if(table[hash]==0)
{
table[hash]=elem;
flag=1;
}
}
}
struct node *separate_chaining(struct node *ptr,int num)
{
struct node *temp,*p;
temp=(struct node *)malloc(sizeof(struct node));
temp->next=NULL;
temp->data=num;
if(ptr==NULL)
{
ptr=temp;
}
else
{
p=ptr;
while(p->next!=NULL)
p=p->next;
p->next=temp;
}
return ptr;
}
void display()
{
for(i=0;i<size;i++)
{
printf("\n %d",table[i]);
if(start[i]!=NULL)
{
struct node *s;
s=start[i];
while(s!=NULL)
{
printf("\t %d",s->data);
s=s->next;
}
}
}
}
void hashing1(int keyValue)
{
hash=(keyValue)%(size);
if(table[hash]==0)
{
table[hash]=keyValue;
return;
}
else
linear_probing(hash,keyValue);
}
void hashing2(int keyValue)
{
hash=(keyValue)%(size);
if(table[hash]==0)
{
table[hash]=keyValue;
return;
}
else
start[hash]=separate_chaining(start[hash],keyValue);
}
int main()
{
int numbers[10],n,opt;
printf("\n Enter the number of eleemnts (less than or equal to %d ):",size);
scanf("%d",&n);
if(n>size)
{
printf("\n Enter the correct number of elements ..");
exit(0);
}
else
{
printf("\n Enter the elements:");
for(i=0;i<n;i++)
scanf("\t %d",&numbers[i]);
printf("1.Linear Probing\n2.Seperate Chaining\nEnter your option:");
scanf("%d",&opt);
switch(opt)
{
case 1:
for(i=0;i<n;i++)
hashing1(numbers[i]);
display();break;
case 2:
for(i=0;i<n;i++)
hashing2(numbers[i]);
display();break;
default:
printf("\nPlease enter crt option");
}
}
}