Skip to content
Snippets Groups Projects
Commit 823239fd authored by Florian Burgener's avatar Florian Burgener
Browse files

Why

parent d0eb86ca
No related branches found
No related tags found
No related merge requests found
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
# t = minimum degree
# minimum of t-1 keys for every node except root
# 2t - 1 keys at most for every node
class Node:
def __init__(self, t):
self.t = t
self.keys = []
self.children = []
self.is_leaf = False
def insert(t, root, key):
if root is None:
root = Node(t)
root.keys = [key]
root.is_leaf = True
return root
insert_index = -1
for i in range(len(root.keys)):
if key < root.keys[i]:
insert_index = i
break
if i == len(root.keys) - 1:
insert_index = i + 1
break
if root.is_leaf and len(root.keys) == 2 * root.t - 1:
parent = Node(root.t)
parent.children = [root]
split_child(parent, 0)
return parent
# parent = Node(root.t)
# root.keys.insert(insert_index, key)
# left = root
# right = Node(root.t)
# split_index = len(root.keys) // 2
# right.keys = root.keys[split_index:]
# left.keys = root.keys[:split_index]
# parent.keys = [right.keys[0]]
# parent.children = [left, right]
if root.is_leaf:
root.keys.insert(insert_index, key)
return root
def split_child(root, i):
left = root.children[i]
split_index = len(root.keys) // 2 + 1
right = Node(root.t)
right.keys = left.keys[split_index:]
left.keys = left.keys[:split_index]
root.children = [left, right]
root.keys = [right.keys[0]]
def main():
t = 2
root = None
root = insert(t, root, 20)
root = insert(t, root, 40)
root = insert(t, root, 5)
root = insert(t, root, 3)
print(root.keys)
print(root.children[0].keys)
print(root.children[1].keys)
if __name__ == "__main__":
main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment