Need help generating a hash table

So hopefully someone here knows something about making hash tables. I have to generate a hash table of load alpha from seq1 which is an array of randomly generated numbers between 0 and 10,000. What I'm having trouble with is actually inserting the numbers into the table. So far my code seems to be getting stuck in a loop or its efficiency is so far gone that my computer cannot produce an answer in a reasonable amount of time. Below is my code for making the hash table where a is the load factor alpha specified by the user (a < 1) and m is the table size, in this case m=9973. Seq1 was created using the randi function.
function [ T ] = MakeAHashTable(seq1,a,m)
n = floor(a.*m);
T = zeros(size(seq1));
index = 1;
i = 0;
while i <= m || n ~= 0
k = seq1(index);
j = mod(k+i,m)+1;
if T(j) == 0
T(j) = k;
index = index+1;
i = 0;
n = n-1;
else i = i+1
end
end
end

1 Comment

Nicholas Colburn
Nicholas Colburn on 12 Mar 2013
Edited: Nicholas Colburn on 12 Mar 2013
I've found by changing the OR comparison to && that this code does indeed work by inserting the seq1 into T. One quick question would be is there any way to initialize T to contain all null? As of now T is created with all zeroes, but what if 0 is a number in seq1? If I wanted to search for that key later on in my code it would be impossible.

Sign in to comment.

 Accepted Answer

Walter Roberson
Walter Roberson on 12 Mar 2013
Where do you change i to be non-zero ?

4 Comments

Nicholas Colburn
Nicholas Colburn on 12 Mar 2013
Edited: Nicholas Colburn on 12 Mar 2013
I've updated my code to reflect where i changes. I had originally used a for loop to insert seq1 and must have forgotten to add the incrementation when I changed to a while loop.
Please recheck your condition i <= m || n ~= 0 . The loop will not exit until both are true. You decrement n towards 0 as you insert elements towards the loading factor, and you increment i as you find used slots, but since you keep going when n = 0 if i <= m, then as long as you find one free slot in that case you will decrement n to -1 and then after that it will never be 0.
Thank you, I just caught that bug a few minutes ago. I commented on the original post about using null and was wondering if you had any insight to offer on that.
No, there is no "null" in numeric matrices. The closest you can get is NaN, which is Not A Number. Note that you cannot compare anything to NaN, because NaN == NaN is false and NaN ~= NaN is also false. You must use isnan() to check for NaN.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!