B树算法的java实现

B树算法及其变种多用于文件,数据库索引,下面是参考“算法导论”的java实现,可以加入节点,没有提供删除结点功能,打印的信息还行,仅供学习。


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/*
* Author: Robert Liu
*/
public class BTree<E extends Comparable<E>> {
private BTNode root = null;
private int t;
private final int fullNum;

public BTree(int t) {
this.t = t;
fullNum = 2 * t - 1;
}

private final BTNode NullBTNode = new BTNode();

private class BTNode {
private int number = 0;
private List<E> values = new ArrayList<E>();
private List<BTNode> children = new ArrayList<BTNode>();
private boolean isLeaf = false;

E getKey(int i) {
return values.get(i);
}

BTNode getChildren(int i) {
return children.get(i);
}

void AddKey(int i, E element) {
values.add(i, element);
}

void removeKey(int i) {
values.remove(i);
}

void AddChildren(int i, BTNode c) {
children.add(i, c);
}

void removeChildren(int i) {
children.remove(i);
}

boolean isFull() {
if (number == fullNum)
return true;
return false;
}

int getSize() {
return values.size();
}

boolean isNull() {
return (this == NullBTNode);
}

@Override
public String toString() {
if (number == 0)
return "NullNode";

StringBuilder sb = new StringBuilder();
sb.append("[N: " + number + "] [values: ");
for (E e : values) {
sb.append(e + ", ");
}
sb.append(" ] [ children: ");
for (BTNode bNode : children) {
if (bNode == NullBTNode)
sb.append(bNode + ", ");
else
sb.append("NotNullNode" + ", ");
}
sb.append("] [childrenSize: " + children.size());
sb.append("] [ isLeaf: " + isLeaf);
sb.append("]");
return sb.toString();
}
}

// Generate the root node
private void constructRoot(E elem) {
root = new BTNode();
root.number = 1;
root.AddKey(0, elem);
root.isLeaf = false;
}

private void addElemToNode(BTNode node, E element, int i) {
node.AddKey(i, element);
node.number++;
node.AddChildren(i, NullBTNode);
}

public void insertElem(E elem) {
if (root == null) {
// The first node
constructRoot(elem);
root.isLeaf = true;
root.AddChildren(0, NullBTNode);
root.AddChildren(1, NullBTNode);
return;
}

BTNode curNode = root;

if (root.isFull()) {
// Extend the root
constructRoot(curNode.getKey(t - 1));

// Get new node
BTNode newNode = getExtendedNode(curNode);

// Process old full node
processFullNode(curNode);

// Process root
root.AddChildren(0, curNode);
root.AddChildren(1, newNode);
return;
}

int i = 0;
BTNode childNode = null;
// Find the node to insert
while (true) {
while ((i < curNode.getSize())
&& (elem.compareTo(curNode.getKey(i)) > 0)) {
i++;
}

childNode = curNode.getChildren(i);
if (childNode.isFull()) {
// Split the node

// Add the element to parent
curNode.number++;
curNode.AddKey(i, childNode.getKey(t - 1));

// New node for extension
BTNode newNode = getExtendedNode(childNode);

// Process old full node
processFullNode(childNode);

// Add the new node for parent reference
curNode.AddChildren(i + 1, newNode);

// Down to low layer
if (elem.compareTo(curNode.getKey(i)) < 0) {
curNode = childNode;
} else {
curNode = newNode;
}
i = 0;
continue;
}

// Down to child node
if (!childNode.isNull()) {
curNode = childNode;
i = 0;
continue;
}

// Insert the element in current node
addElemToNode(curNode, elem, i);
return;
}

}

private BTNode getExtendedNode(BTNode fullNode) {
BTNode newNode = new BTNode();
newNode.number = t - 1;
newNode.isLeaf = fullNode.isLeaf;
for (int i = 0; i < t; i++) {
if (i != t - 1) {
newNode.AddKey(i, fullNode.getKey(t + i));
}
newNode.AddChildren(i, fullNode.getChildren(t + i));
}
return newNode;
}

// Should be called after calling getExtendedNode()
private void processFullNode(BTNode fullNode) {
fullNode.number = t - 1;
for (int i = t - 1; i >= 0; i--) {
fullNode.removeKey(t + i - 1);
fullNode.removeChildren(t + i);
}
}

@Override
public String toString() {
if (root == null)
return "NULL";

StringBuilder sb = new StringBuilder();

LinkedList<BTNode> queue = new LinkedList<BTNode>();
queue.push(root);

BTNode tem = null;
while ((tem = queue.poll()) != null) {
for (BTNode node : tem.children) {
if (!node.isNull())
queue.offer(node);
}
sb.append(tem.toString() + "\n");
}
return sb.toString();
}

public static void main(String[] args) {
BTree<Character> tree = new BTree<Character>(3);
System.out.println(tree);
Character[] cL = { 'D', 'E', 'F', 'A', 'C', 'B', 'Z', 'H', 'I', 'J' };
for (int i = 0; i < cL.length; i++) {
tree.insertElem(cL[i]);
System.out.println("After insert the: " + cL[i]);
System.out.println(tree);
}
}
output
===================
NULL
After insert the: D
[N: 1] [values: D, ] [ children: NullNode, NullNode, ] [childrenSize: 2] [ isLeaf: true]

After insert the: E
[N: 2] [values: D, E, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]

After insert the: F
[N: 3] [values: D, E, F, ] [ children: NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 4] [ isLeaf: true]

After insert the: A
[N: 4] [values: A, D, E, F, ] [ children: NullNode, NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 5] [ isLeaf: true]

After insert the: C
[N: 5] [values: A, C, D, E, F, ] [ children: NullNode, NullNode, NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 6] [ isLeaf: true]

After insert the: B
[N: 1] [values: D, ] [ children: NotNullNode, NotNullNode, ] [childrenSize: 2] [ isLeaf: false]
[N: 2] [values: A, C, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 2] [values: E, F, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]

After insert the: Z
[N: 1] [values: D, ] [ children: NotNullNode, NotNullNode, ] [childrenSize: 2] [ isLeaf: false]
[N: 2] [values: A, C, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 3] [values: E, F, Z, ] [ children: NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 4] [ isLeaf: true]

After insert the: H
[N: 1] [values: D, ] [ children: NotNullNode, NotNullNode, ] [childrenSize: 2] [ isLeaf: false]
[N: 2] [values: A, C, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 4] [values: E, F, H, Z, ] [ children: NullNode, NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 5] [ isLeaf: true]

After insert the: I
[N: 1] [values: D, ] [ children: NotNullNode, NotNullNode, ] [childrenSize: 2] [ isLeaf: false]
[N: 2] [values: A, C, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 5] [values: E, F, H, I, Z, ] [ children: NullNode, NullNode, NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 6] [ isLeaf: true]

After insert the: J
[N: 2] [values: D, H, ] [ children: NotNullNode, NotNullNode, NotNullNode, ] [childrenSize: 3] [ isLeaf: false]
[N: 2] [values: A, C, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 2] [values: E, F, ] [ children: NullNode, NullNode, NullNode, ] [childrenSize: 3] [ isLeaf: true]
[N: 3] [values: I, J, Z, ] [ children: NullNode, NullNode, NullNode, NullNode, ] [childrenSize: 4] [ isLeaf: true]
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
B+树是一种常用的数据结构,它是一种多路搜索树,通常用于数据库和文件系统中。以下是B+树的Java实现。 首先,我们需要定义一个B+树节点的类,它包含一个存储键值对的数组和一个指向子节点的数组。 ```java public class BPlusTreeNode { private int[] keys; private BPlusTreeNode[] children; } ``` 接下来,我们创建一个B+树类,它包含一个根节点和一个阶数,阶数决定了每个节点最多可以包含多少个子节点和键值对。 ```java public class BPlusTree { private BPlusTreeNode root; private int order; } ``` 现在,我们来实现B+树的插入操作。插入操作首先需要找到插入位置,然后将键值对插入到叶子节点中。如果插入后叶子节点的键值对个数超过了阶数,我们需要进行分裂操作,将叶子节点分裂成两个节点,并将中间的键值对插入到父节点中。 ```java public void insert(int key, Object value) { if (root == null) { root = new BPlusTreeNode(); root.keys[0] = key; root.children[0] = new BPlusTreeNode(value); return; } BPlusTreeNode leaf = findLeafNode(key); if (leaf.isFull()) { BPlusTreeNode newLeaf = leaf.split(); if (leaf == root) { root = new BPlusTreeNode(); root.keys[0] = newLeaf.keys[0]; root.children[0] = leaf; root.children[1] = newLeaf; return; } BPlusTreeNode parent = findParentNode(leaf); parent.insertChild(newLeaf.keys[0], newLeaf); } leaf.insertKey(key, value); } ``` 接下来,我们需要实现B+树的查找操作。查找操作从根节点开始,根据键值比较找到正确的叶子节点,然后在叶子节点中查找对应的键值对。 ```java public Object find(int key) { BPlusTreeNode leaf = findLeafNode(key); return leaf.getValue(key); } ``` 最后,我们还需要实现B+树的删除操作。删除操作首先需要找到要删除的键值对所在的叶子节点,然后将该键值对从叶子节点中删除。如果删除后叶子节点的键值对个数小于阶数的一半,我们需要进行合并操作,将该节点和相邻的兄弟节点合并成一个节点,并将中间的键值对从父节点中删除。 ```java public void delete(int key) { BPlusTreeNode leaf = findLeafNode(key); leaf.deleteKey(key); if (leaf.isEmpty()) { BPlusTreeNode parent = findParentNode(leaf); BPlusTreeNode sibling = siblingNode(leaf); if (sibling != null && sibling.canMerge()) { parent.merge(sibling); } else if (parent != null) { parent.removeChild(leaf); } } } ``` 上述是B+树的简单实现,可以根据实际需求进行扩展和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值