Building the index (Algorithm 1)·7 min
The insert algorithm
0 / 1
Algorithm 1 assembles everything you have built. To insert a new element q:
- Draw its level
l(the seeded dice from Chapter 1). - Descend from the current top layer down to
l+1withSEARCH-LAYERatef = 1— just walk towardq, no result set, to find a good entry point for the next phase. - Wire edges from
min(l, topLayer)down to 0: at each layer runSEARCH-LAYERatefConstruction,SELECT-NEIGHBORSfrom the results, add bidirectional edges, then for each new neighbor whose degree now exceedsMmax(Mmax0at layer 0) shrink its neighbor list. - Promote
qto entry point iflexceeds the current top layer.
Algorithm 1 skeleton
l <- assignLevel()
ep <- [entryPoint]
for lc from topLayer down to l+1: // greedy descent, ef=1
ep <- [ nearest of SEARCH-LAYER(q, ep, 1, lc) ]
for lc from min(topLayer, l) down to 0: // wire edges, ef=efConstruction
W <- SEARCH-LAYER(q, ep, efConstruction, lc)
nbs <- SELECT-NEIGHBORS(q, W, M)
connect(lc, q, nbs, Mmax_for(lc)) // bidirectional + shrink
ep <- W
if l > topLayer: topLayer <- l; entryPoint <- q
Edges are bidirectional and capacity-bounded
When you add new ↔ neighbor, the neighbor may now exceed Mmax. You must re-select its neighborhood with the heuristic and possibly drop an old edge. Forgetting to shrink makes hub nodes with thousands of edges — slow and memory-blown. Shrinking with the heuristic (keeping pruned connections) is also what preserves layer-0 connectivity.