Hash table average search length calculation problem

[408-2019 August] The
existing hash table HT with a length of 11 and initially empty, the hash function is H(key) = key %7, and a linear probe (linear probe and then hash) method is used to resolve conflicts. After the sequences 87, 40, 30, 6, 11, 22, 98, and 20 are inserted into HT in turn, the average search length of HT search failure is

A. 4
B.5.25
C.6
D.6.29

Answer: C

Analysis:
1. Construct a hash table
According to the hash function H(key) = key %7 and linear re-detection, we can construct a hash table, as shown in the figure belowInsert picture description here

2. Calculate the average search length that failed

If the calculation fails, it can be converted and understood, that is, how many times do we need to compare a new value when we insert a new value on the already constructed hash table.

For example, now I insert a number 21, then theoretically it should be stored at address 0, but address 0 has 98, then we linearly detect again (that is, add an address in turn to see if it is empty, and insert it if it is empty) In the same way, there are also elements at address 1. By analogy, we have to compare addresses 0~7 in total, and found that all have values, until the comparison address 8 is empty. So a total of 9 comparisons were made.

To understand the other addresses (0~6) in the same way, the total number of comparisons is 9+8+7+6+5+4+3 = 42

It should be noted here that because our modulus is 7, the calculated address can only be in the range (0~6), so the final result is 42/7 =6

3. Calculate the average search length
of success. Calculate the length of success. It means to record how many times each value is compared to find the storage space.
For example, the number of times each value in this question is compared (and saved) to the corresponding address is as shown in the figure below.
Insert picture description here

So its ASL = 1+1+1+1+1+1+1+1/8=1

note
1. Note that the meaning of the denominator of the failed and successful search lengths is different. When it fails, the denominator is the value of the modulus; when it succeeds, the denominator is the number of elements.

Guess you like

Origin blog.csdn.net/qq_34902437/article/details/103239901