Skip to content

Instantly share code, notes, and snippets.

@nlowe
Last active May 22, 2023 15:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nlowe/6e2bf999d53b2bb31321d30aafdd510a to your computer and use it in GitHub Desktop.
Save nlowe/6e2bf999d53b2bb31321d30aafdd510a to your computer and use it in GitHub Desktop.
BTree pseudocode from the slides
# Not actually python, but that's the closest language to the pseudocode dialect the book uses
B-Tree-Search(x, k)
i = 1
while i ≤ x.n and k > x.key[i]
i = i + 1
if i ≤ x.n and k == x.key[i]
return (x, i)
if x.leaf
return nil
else Disk-Read(x.c[i])
return B-Tree-Search(x.c[i], k)
B-Tree-Create(T)
x = Allocate-Node()
x.leaf = true
x.n = 0
Disk-Write(x)
T.root = x
B-Tree-Split-Child(x, i)
z = Allocate-Node()
y = x.c[i]
z.leaf = y.leaf
z.n = t – 1
for j = 1 to t – 1
z.key[j] = y.key[j+t]
if not y.leaf
for j = 1 to t
z.c[j] = y.c[j+t]
y.n = t – 1
for j = x.n + 1 downto i + 1
x.c[j+1] = x.c[j]
x.c[i+1] = z
for j = x.n downto i
x.key[j+1] = x.key[j]
x.key[i] = y.key[t]
x.n = x.n+1
Disk-Write(y)
Disk-Write(z)
Disk-Write(x)
B-Tree-Insert(T, k)
r = T.root
if r.n == 2t – 1 # if the root node is full, split it:
s = Allocate-Node() # get a new node
T.root = s # which will be the new root
s.leaf = false # which means it’s not a leaf
s.n = 0 # it currently has no keys
s.c[1] = r # its lone child is the old root
B-Tree-SplitChild(s, 1) # Split the (full) child (old root)
B-Tree-Insert-NonFull(s, k) # Now we have room to ins
else B-Tree-Insert-NonFull(r, k) # Else, we already had room
B-Tree-Insert-NonFull(x, k)
i = x.n
if x.leaf
while i ≥ 1 and k < x.key[i]
x.key[i+1] = x.key[i]
i = i – 1
x.key[i+1] = k
x.n = x.n + 1
Disk-Write(x)
else
while i ≥ 1 and k < x.keyi
i = i – 1
i = i + 1
Disk-Read(x.c[i])
if x.c[i].n == 2t – 1
B-Tree-Split-Child(x, i, x.c[i])
if k > x.key[i]
i = i + 1
B-Tree-Insert-NonFull(x.c[i], k)
@FoxieFlakey
Copy link

a few questions:

  1. Is array, zero based
  2. Is the Disk-Write can be no-op if used as in memory data structure?
  3. Is assuming that deletion is B-Tree-Search but overwrites existing with nil correct?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment