Write a simple C++ program which will identify how many collisions occur for eac
ID: 3572500 • Letter: W
Question
Write a simple C++ program which will identify how many collisions occur for each of the numbers from 200 thru 600, incremented by 5, when mapping to a hash table array of 100 entries.
Do this by creating a variable and looping to force it to have all values: 200, 205, 210… 600.
First use 100 as the divisor and use the modulo function to do mapping. Then use 101 as the divisor with the modulo function to do the mapping.
Separately, set up an array of 100 entries, whose values will be a count of the number of times its index is created. Initialize to zero.
For example: 200 maps to index value ‘i’ = 99. Add 1 to Array[99].
Output the 101 results to see how the distribution would occur.
Explanation / Answer
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
class Hash
{
private:
int a[MAX];
public:
Hash();
int create(int);
void linear_prob(int,int),display();
};
Hash::Hash()
{
int i;
for(i=0;i<MAX;i++)
a[i]=-1;
}
int Hash::create(int num)
{
int key;
key=num%10;
return key;
}
void Hash::linear_prob(int key,int num)
{
int flag,i,count=0;
flag=0;
if(a[key]==-1)//if the location indicated by hash key is empty
a[key]=num;//place the number in the hash table
else
{
i=0;
while(i<MAX)
{
if(a[i]!=-1)
count++;
i++;
}
if(count==MAX) //checking for the hash full
{
cout<<" Hash Table Is Full Hence "<<num<<" Can not Be Inserted";
display();
getch();
exit(1);
}
for(i=key+1;i<MAX;i++)//moving linearly down
if(a[i]==-1) // searching for empty location
{
a[i]=num; //placing the number at empty location
flag=1;
break;
}
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}
} //outer else
}//end
void Hash::display()
{
int i;
cout<<" The Hash Table is..."<<endl;
for(i=0;i<MAX;i++)
cout<<" "<<i<<" "<<a[i];
}
void main()
{
int num,key;
char ans;
Hash h;
clrscr();
cout<<" Collision Handling By Linear Probing";
do
{
cout<<" Enter The Number";
cin>>num;
key=h.create(num);
h.linear_prob(key,num);
cout<<" Do U Wish To Continue?(y/n)";
ans=getche();
}while(ans=='y');
h.display();
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.