I am looking at skip list implementation in Java , and I am wondering the purpose of the following method:
public static int randomLevel() {
int lvl = (int)(Math.log(1.-Math.random())/Math.log(1.-P));
return Math.min(lvl, MAX_LEVEL);
}
And what the difference between the above method and
Random.nextInt(6);
Can anyone explain that? Thanks.
Random.nextIntshould provide a random variable whose probability distribution is (approximately) a discrete uniform distribution over the interval [0, 6).You can learn more about this here.
http://puu.sh/XMwn
Note that internally
Randomuses a linear congruential generator where m = 2^48, a = 25214903917, and c = 11.randomLevelinstead (approximately) uses a geometric distribution where p = 0.5. You can learn more about the distribution here.http://puu.sh/XMwT
Essentially,
randomLevelreturns0with probability 0.5,1with 0.25,2with 0.125, etc. until6with 0.5^7 i.e. *0.0078125** — far different than the ~0.14 fromRandom.nextInt.Now the importance of this is that a skip list is an inherently probabilistic data structure. By utilizing multiple sparse levels of linked lists, they can achieve average runtime performance of O(log n) search — similar to a balanced binary search tree, but less complex and using less space. Using a uniform distribution here would not be appropriate, seeing how to as higher levels are less densely populated in comparison to lower ones (note: below, the levels grow downward) — which is necessary for the fast searches.