import
java.util.ArrayList;
class
BTreeNode {
private
ArrayList<Integer> keys;
private
int
t;
private
ArrayList<BTreeNode> C;
private
boolean
leaf;
public
BTreeNode(
int
t,
boolean
leaf) {
this
.t = t;
this
.leaf = leaf;
this
.keys =
new
ArrayList<>();
this
.C =
new
ArrayList<>();
}
public
void
traverse(
int
tab) {
StringBuilder s =
new
StringBuilder();
for
(
int
j =
0
; j < tab; j++) {
s.append(
'\t'
);
}
for
(
int
i =
0
; i < keys.size(); i++) {
if
(!leaf) {
C.get(i).traverse(tab +
1
);
}
System.out.println(s.toString() + keys.get(i));
}
if
(!leaf) {
C.get(keys.size()).traverse(tab +
1
);
}
}
public
boolean
isFull() {
return
keys.size() ==
2
* t -
1
;
}
public
BTreeNode makeNewRoot(
int
val, BTreeNode newEntry) {
BTreeNode root =
new
BTreeNode(t,
false
);
root.keys.add(val);
root.C.add(
this
);
root.C.add(newEntry);
return
root;
}
public
void
split(
int
[] val, BTreeNode newEntry) {
BTreeNode newNode =
new
BTreeNode(t,
false
);
val[
0
] =
this
.keys.get(t);
for
(
int
i = t +
1
; i <
2
* t; i++) {
newNode.keys.add(
this
.keys.get(i));
}
this
.keys.subList(t,
2
* t -
1
).clear();
newNode.C.addAll(
this
.C.subList(t +
1
,
2
* t));
this
.C.subList(t +
1
,
2
* t +
1
).clear();
this
.C.add(newNode);
}
public
void
insert(
int
newKey,
int
[] val, BTreeNode[] newEntry) {
if
(!leaf) {
int
i =
0
;
while
(i < keys.size() && newKey > keys.get(i))
i++;
C.get(i).insert(newKey, val, newEntry);
if
(newEntry[
0
] ==
null
)
return
;
if
(keys.size() <
2
* t -
1
) {
keys.add(i, val[
0
]);
C.add(i +
1
, newEntry[
0
]);
newEntry[
0
] =
null
;
}
else
{
keys.add(i, val[
0
]);
C.add(i +
1
, newEntry[
0
]);
split(val, newEntry[
0
]);
}
}
else
{
int
i =
0
;
while
(i < keys.size() && newKey > keys.get(i))
i++;
keys.add(i, newKey);
if
(keys.size() ==
2
* t) {
BTreeNode newLeaf =
new
BTreeNode(t,
true
);
val[
0
] =
this
.keys.get(t);
newLeaf.keys.addAll(keys.subList(t +
1
,
2
* t));
this
.keys.subList(t,
2
* t -
1
).clear();
newEntry[
0
] = newLeaf;
}
}
}
}
class
BTree {
private
BTreeNode root;
private
int
t;
public
BTree(
int
t) {
this
.root =
new
BTreeNode(t,
true
);
this
.t = t;
}
public
void
insert(
int
key) {
BTreeNode[] newEntry = {
null
};
int
[] val = {
0
};
root.insert(key, val, newEntry);
if
(newEntry[
0
] !=
null
) {
root = root.makeNewRoot(val[
0
], newEntry[
0
]);
}
}
public
void
display() {
root.traverse(
0
);
}
}
public
class
Main {
public
static
void
main(String[] args) {
BTree tree =
new
BTree(
3
);
System.out.println(
"After inserting 1 and 2"
);
tree.insert(
1
);
tree.insert(
2
);
tree.display();
System.out.println(
"After inserting 5 and 6"
);
tree.insert(
5
);
tree.insert(
6
);
tree.display();
System.out.println(
"After inserting 3 and 4"
);
tree.insert(
3
);
tree.insert(
4
);
tree.display();
}
}