diff --git a/.archive/bplustree.go b/bplustree.go similarity index 99% rename from .archive/bplustree.go rename to bplustree.go index 79a257a..7fdab1b 100644 --- a/.archive/bplustree.go +++ b/bplustree.go @@ -100,14 +100,14 @@ func (tree *BPlusTree) Insert(key int, value interface{}) { index := sort.SearchInts(leaf.keys, key) leaf.keys = append(leaf.keys[:index], append([]int{key}, leaf.keys[index:]...)...) + if len(leaf.keys) > int(tree.maxKeys) { + tree.splitNode(leaf) + } + if len(tree.root.keys) > int(tree.maxKeys) { tree.SplitRoot() return } - - if len(leaf.keys) > int(tree.maxKeys) { - tree.splitNode(leaf) - } } func (tree *BPlusTree) findLeaf(key int) *BPlusTreeNode { @@ -149,7 +149,7 @@ func (tree *BPlusTree) SplitRoot() { // split the node in two mid := len(root.keys) / 2 leftKeys := root.keys[:mid] - rightKeys := root.keys[mid:] + rightKeys := root.keys[mid+1:] leftChildren := []*BPlusTreeNode{} rightChildren := []*BPlusTreeNode{} diff --git a/.archive/bplustree_test.go b/bplustree_test.go similarity index 73% rename from .archive/bplustree_test.go rename to bplustree_test.go index 75b7e26..af12299 100644 --- a/.archive/bplustree_test.go +++ b/bplustree_test.go @@ -79,9 +79,6 @@ func TestIsShapedCorrectlyAfter5(t *testing.T) { tree.Insert(key, fmt.Sprintf("Node #%d", key)) } - tree.Print() - return - // root assert.Equal(t, []int{3}, tree.root.keys) @@ -91,12 +88,40 @@ func TestIsShapedCorrectlyAfter5(t *testing.T) { // 3rd layer // left - assert.Equal(t, []int{1}, tree.root.children[0].children[0]) - assert.Equal(t, []int{2}, tree.root.children[0].children[1]) + assert.Equal(t, []int{1}, tree.root.children[0].children[0].keys) + assert.Equal(t, []int{2}, tree.root.children[0].children[1].keys) + + // right + assert.Equal(t, []int{3}, tree.root.children[1].children[0].keys) + assert.Equal(t, []int{4, 5}, tree.root.children[1].children[1].keys) + + tree.Print() +} + +func TestIsShapedCorrectlyAfter6(t *testing.T) { + tree := NewBPlusTree(3) + keys := []int{1, 2, 3, 4, 5, 6} + + for _, key := range keys { + tree.Insert(key, fmt.Sprintf("Node #%d", key)) + } + + // root + assert.Equal(t, []int{3}, tree.root.keys) + + // 2nd layer + assert.Equal(t, []int{2}, tree.root.children[0].keys) // right + assert.Equal(t, []int{4, 5}, tree.root.children[1].keys) // left + + // 3rd layer + // left + assert.Equal(t, []int{1}, tree.root.children[0].children[0].keys) + assert.Equal(t, []int{2}, tree.root.children[0].children[1].keys) // right - assert.Equal(t, []int{3}, tree.root.children[1].children[0]) - assert.Equal(t, []int{4, 5}, tree.root.children[1].children[1]) + assert.Equal(t, []int{3}, tree.root.children[1].children[0].keys) + assert.Equal(t, []int{4}, tree.root.children[1].children[1].keys) + assert.Equal(t, []int{5, 6}, tree.root.children[1].children[2].keys) tree.Print() }