I have commented the portion where I am facing a problem. I have to tell whether the array is full or not if it's full then return. Kindly help! Thanks!
#include <iostream>
usingnamespace std;
int hashfun(int y, int size)
{
int m = y % size;
return m;
}
void insert(int x,int arr[])
{
int data, index;
int i = 0;
for (int k = 0; k < x; k++)
{
cout << "Enter Data to Store: ";
cin >> data;
index = hashfun(data, x);
int j = 0;
while (index + j % x != 0 && j < x)
{
j++;
}
// here I have to write an if statement to check if the array
//is full! If it is full then return
//else run the below condition
arr[index + j % x] = data;
}
}
void show(int x, int arr[])
{
for (int i = 0; i < x; i++)
{
cout << "Index " << i << ": " << arr[i] << endl;
}
}
int main()
{
int size, size1, index;
int data;
cout << "Enter size of array:" << endl;
cin >> size;
int *ptr = newint[size];
for (int i = 0; i < size; i++)
{
ptr[i] = 0;
}
cout << "How Much Data You Want to Enter\n";
cin >> size1;
insert(size1, ptr);
show(size1, ptr);
system("pause");
}
The array always contains data. Every element of the array always has a value in. Always. Always. From the moment the array is created until the moment it is destroyed, it is always full of data. Either data you wrote, or just whatever happens by chance to be in that piece of memory.
If I don’t misunderstand your code, ‘arr’ will be full when k == x - 1.
But Repeater has a very good point: your question (and let me say your code too) is not clear.
you have a few options...
1) make a little struct with a 'in use' boolean:
struct mydata
{
bool in_use; int data;
};
and let your code use the in_use variable (set to false by default, maybe add a ctor to do that to the struct).
2) side by side array of bool, same idea, but its no longer in the data.
3) counter to track # of locations used. this means you also need a sentinel value in the array to tell if a slot is used or not, though, and sentinels are sometimes risky (it is a valid value!)
4) stop using probing, which is troublesome, and consider making a 2-d chained approach.
What's going on at lines 18-20? Those lines just set j=0 or j=x. Did you mean (index+j) % x? What you have is parsed as index + (j%x) although I think (index+j) % x would result in you always storing at index 0.
Let's back up. Can you explain what you're trying to do with this program? How is your hash table supposed to work?