跳表C语言实现中插入层级概率控制的Rand函数原理解析
Rand() Function's Probability Logic Great question! This Rand() function is a clever, compact way to enforce the skip list's core probability rule—let's unpack it step by step.
First, let's restate the goal we need to hit: a new node should have its highest level as i with probability 1/2^i. That translates to:
- 1/2 chance the node only exists on the bottom level (highest level = 1)
- 1/4 chance it extends up to level 2
- 1/8 chance up to level 3, and so on
Breaking Down the Code
Let's walk through each part of the function line by line:
static int Rand() { int i, j = 0; uint32_t t = rand(); for (i = 1, j = 2; i < lg_n_max; i ++, j += j) if (t > RANDMAX / j) break; if (i > lg_n) lg_n = i; return i; }
- Random Number Base:
t = rand()generates a random integer between0andRANDMAX(the maximum valuerand()can return, like 32767 for standard C implementations). - Loop Initialization: We start with
i=1(the lowest possible level for a new node) andj=2—noticejis always2^ihere (starts at2^1=2, then doubles each loop iteration). - Probability Check Loop:
- For each level
i, we split the full random number range intojequal slices (sinceRANDMAX/jis the size of each slice). - If
tfalls into the upper(j-1)/jportion of the range (i.e.,t > RANDMAX/j), we stop the loop and returnias the node's highest level. - If
tis in the bottom1/jslice, we keep going: incrementito try the next higher level, and doublej(so we split the range into twice as many slices for the next check).
- For each level
Why This Gives the Exact Probabilities We Need
Let's map this logic to our target probabilities:
- Returning
i=1: This happens whent > RANDMAX/2(the upper half of the random range). The probability of this is1/2 = 1/2^1—exactly what we want for nodes limited to the bottom level. - Returning
i=2: This only occurs ift ≤ RANDMAX/2(probability1/2) ANDt > RANDMAX/4. The interval(RANDMAX/4, RANDMAX/2]makes up 1/4 of the total range, so the combined probability is1/4 = 1/2^2. - Returning
i=3: We only get here ift ≤ RANDMAX/4(probability1/4), then check ift > RANDMAX/8. The interval(RANDMAX/8, RANDMAX/4]is 1/8 of the total range—so probability1/8 = 1/2^3. - And so on: For any level
i, the probability of returningiis exactly1/2^i, which matches the skip list's requirement perfectly.
The Final lg_n Update
The line if (i > lg_n) lg_n = i just tracks the highest level currently present in the skip list. When we generate a level higher than the current maximum, we update lg_n so future insertions can use this higher level, ensuring the skip list scales naturally as more elements are added.
内容的提问来源于stack exchange,提问作者纪老猴子

