-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBtreeSML.java
1987 lines (1815 loc) · 128 KB
/
BtreeSML.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// BtreeStuckStatic in bit memory
// Philip R Brenan at appaapps dot com, Appa Apps Ltd Inc., 2024
//------------------------------------------------------------------------------
package com.AppaApps.Silicon; // Design, simulate and layout a btree in a block on the surface of a silicon chip.
import java.util.*;
abstract class BtreeSML extends Test // Manipulate a btree using static methods and memory
{MemoryLayout memoryLayout = new MemoryLayout(); // The memory layout of the btree
abstract int maxSize(); // The maxuimum bunber of leaves plus branches in the bree
abstract int bitsPerKey(); // The number of bits per key
abstract int bitsPerData(); // The number of bits per data
abstract int bitsPerNext(); // The number of bits in a next field
abstract int bitsPerSize(); // The number of bits in size field
abstract int maxKeysPerLeaf(); // Maximum number of leafs in a key
abstract int maxKeysPerBranch(); // Maximum number of keys in a branch
int splitLeafSize () {return maxKeysPerLeaf() >> 1;} // The number of key, data pairs to split out of a leaf
int splitBranchSize() {return maxKeysPerBranch() >> 1;} // The number of key, next pairs to split out of a branch
StuckSML Leaf; // Leaf definition
StuckSML Branch; // Branch defintion
Layout.Field leaf; // Layout of a leaf in the memory used by btree
Layout.Field branch; // Layout of a branch in the memory used by btree
Layout.Union branchOrLeaf; // Layout of either a leaf or a branch in the memory used by btree
Layout.Bit isLeaf; // Whether the current node is a leaf or a branch
Layout.Variable free; // Free list chain
Layout.Structure node; // Layout of a node in the memory used by btree
Layout.Array nodes; // Layout of an array of nodes in the memory used by btree
Layout.Variable freedChain; // Single linked list of freed nodes
Layout.Structure bTree; // Btree
final static int
linesToPrintABranch = 4, // The number of lines required to print a branch
maxPrintLevels = 10, // Maximum number of levels to print in a tree
maxDepth = 99, // Maximum depth of any realistic tree
testMaxSize = github_actions ? 1000 : 50; // Maximum number of leaves plus branchs during testing
int nodeUsed = 0; // Number of nodes currently in use
int maxNodeUsed = 0; // Maximum number of branches plus leaves used
final Node root; // The description ofthe root node
final Node parentNode; // Node used for initializing the tree and for the parent node
final Node leftNode; // Node used for a left hand child
final Node rightNode; // Node used for a righthand child
final Node childNode; // Node used as a generic child
final Node tempNode; // Temporary node
final Node findNode; // Find node
final Node putNode; // Put node
final Node deleteNode; // Delete node
static boolean debug = false; // Debugging enabled
//D1 Construction // Create a BTree from nodes which can be branches or leaves. The data associated with the BTree is stored only in the leaves opposite the keys
BtreeSML() // Define a BTree with user specified dimensions
{z();
memoryLayout.layout = layout();
memoryLayout.memory(new Memory("BtreeSML", memoryLayout.layout.size()));
root = new Node(); // The description ofthe root node
parentNode = new Node(); // Node used for initializing the tree and for the parent node
leftNode = new Node(); // Node used for a left hand child
rightNode = new Node(); // Node used for a righthand child
childNode = new Node(); // Node used as a generic child
tempNode = new Node(); // Temporary node
findNode = new Node(); // Find node
putNode = new Node(); // Put node
deleteNode = new Node(); // Delete node
for (int i = maxSize(); i > 0; --i) // Put all the nodes on the free chain at the start with low nodes first
{final Node n = parentNode;
n.node = i - 1;
n.clear();
final int f = getInt(freedChain);
setInt(free, f, n.node);
setInt(freedChain, n.node);
}
allocate(root, false); // The root is always at zero, which frees zero to act as the end of list marker on the free chain
root.setLeaf(); // The root starts as a leaf
root.setStucks(); // Describe stucks addressable fronm the root
}
static BtreeSML btreeSML(final int leafKeys, int branchKeys) // Define a test BTree with the specified dimensions
{return new BtreeSML()
{int maxSize () {return testMaxSize;}
int maxKeysPerLeaf () {return leafKeys;}
int maxKeysPerBranch() {return branchKeys;}
int bitsPerKey () {return 16;}
int bitsPerData () {return 16;}
int bitsPerNext () {return 16;}
int bitsPerSize () {return 16;}
};
}
Layout layout() // Layout describing memory used by btree
{z();
final BtreeSML btree = this;
Leaf = new StuckSML() // Leaf
{int maxSize() {return btree.maxKeysPerLeaf();}
int bitsPerKey() {return btree.bitsPerKey();}
int bitsPerData() {return btree.bitsPerData();}
int bitsPerSize() {return btree.bitsPerSize();}
};
Branch = new StuckSML() // Branch
{int maxSize() {return btree.maxKeysPerBranch()+1;} // Not forgetting top next
int bitsPerKey() {return btree.bitsPerKey();}
int bitsPerData() {return btree.bitsPerNext();}
int bitsPerSize() {return btree.bitsPerSize();}
};
final Layout l = Layout.layout();
leaf = l.duplicate("leaf", Leaf .layout());
branch = l.duplicate("branch", Branch.layout());
branchOrLeaf = l.union ("branchOrLeaf", leaf, branch);
isLeaf = l.bit ("isLeaf");
free = l.variable ("free", btree.bitsPerNext());
node = l.structure("node", isLeaf, free, branchOrLeaf);
nodes = l.array ("nodes", node, maxSize());
freedChain = l.variable ("freedChain", btree.bitsPerNext());
bTree = l.structure("bTree", freedChain , nodes);
return l.compile();
}
void fixMemory(Memory memory) // Fix memory so that we can use the methods in this implementation of btree against memory created by other implementations of btree as a long as they use the same memory layout
{memoryLayout .memory(memory); // Refer to supplied memory
root.Leaf .M.memory(memory); // Fix leaf stuck of root
root.Branch.M.memory(memory); // Fix branch stuck of root
root.setStucks(); // Set base addresses for the leaf and branch stucks used by the root
}
//D1 Control // Testing, control and integrity
void ok(String expected) {Test.ok(toString(), expected);} // Confirm tree is as expected
void stop() {Test.stop(toString());} // Stop after printing the tree
public String toString() {return print();} // Print the tree
//D1 Memory access // Access to memory
int getInt(Layout.Field field) {z(); return memoryLayout.getInt(field);}
int getInt(Layout.Field field, int index) {z(); return memoryLayout.getInt(field, index);}
void setInt(Layout.Field field, int value) {z(); memoryLayout.setInt(field, value);}
void setInt(Layout.Field field, int value, int index) {z(); memoryLayout.setInt(field, value, index);}
//D1 Memory allocation // Allocate and free memory
void allocate(Node node, boolean check) // Allocate a node with or without checking for sufficient free space
{z(); final int f = getInt(freedChain); // Last freed node
z(); if (check && f == 0) stop("No more memory available"); // No more free nodes available
z(); final int F = getInt(free, f); // Second to last freed node
setInt(freedChain, F); // Make second to last freed node the forst freed nod to liberate the existeing first free node
node.node = f; node.clear(); // Construct and clear the node
maxNodeUsed = max(maxNodeUsed, ++nodeUsed); // Number of nodes in use
// return n;
}
void allocate(Node node) {z(); allocate(node, true);} // Allocate a node checking for free space
//D1 Components // A branch or leaf in the tree
class Node // A branch or leaf in the tree
{int node; // The number of the node
StuckSML Leaf, Branch; // Stucks used in this node with their base addresses set corrctly to allow addressing of the fields in the stuck
Node()
{Leaf = BtreeSML.this.Leaf.copy(); // Address the leaf stuck
Leaf.M.memory(BtreeSML.this.memoryLayout.memory);
Branch = BtreeSML.this.Branch.copy(); // Address the branch stuck
Branch.M.memory(BtreeSML.this.memoryLayout.memory);
}
boolean isLeaf() {z(); return getInt(isLeaf, node) > 0;} // A leaf if true
void setLeaf() {z(); setInt(isLeaf, 1, node);} // Set as leaf
void setBranch() {z(); setInt(isLeaf, 0, node);} // Set as branch
void assertLeaf() {if (!isLeaf()) stop("Leaf required");}
void assertBranch() {if ( isLeaf()) stop("Branch required");}
Node allocLeaf(Node node) // Allocate leaf
{z(); allocate(node); node.setLeaf(); node.setStucks();
return node;
}
Node allocBranch(Node node) // Allocate branch
{z(); allocate(node); node.setBranch(); node.setStucks();
return node;
}
void setStucks() // Descriptions of the stucks addressed by this node setting their base offsets
{Leaf.base(leafBase());
Branch.base(branchBase());
}
void free() // Free a new node to make it available for reuse
{z(); if (node == 0) stop("Cannot free root"); // The root is never freed
z(); erase(); // Clear the node to encourage erroneous frees to do damage that shows up quickly.
final int f = getInt(freedChain); // Last freed node from head of free chain
setInt(free, f, node); // Chain this node in front of the last freed node
setInt(freedChain, node); // Make this node the head of the free chain
maxNodeUsed = max(maxNodeUsed, --nodeUsed); // Number of nodes in use
}
void clear() // Clear a new node to zeros ready for use
{z();
final Layout.Field n = BtreeSML.this.node;
final int at = n.at(node), w = n.width;
BtreeSML.this.memoryLayout.memory.zero(at, w);
}
void erase() // Clear a new node to ones as this is likely to create invalid values that will be easily detected in the case of erroneous frees
{z();
final Layout.Field n = BtreeSML.this.node;
final int at = n.at(node), w = n.width;
BtreeSML.this.memoryLayout.memory.ones(at, w);
}
int leafBase() {z(); return leaf .at(node);} // Base of leaf stuck in memory
int branchBase() {z(); return branch.at(node);} // Base of branch stuck in memory
int leafSize() {z(); return Leaf.size();} // Number of children in body of leaf
int branchSize() {z(); return Branch.size()-1;} // Number of children in body of branch taking top for granted as it is always there
boolean isFull() // The node is full
{z(); return isLeaf() ? leafSize() == maxKeysPerLeaf ():
branchSize() == maxKeysPerBranch();
}
boolean isLow() {z(); return (isLeaf() ? leafSize() : branchSize()) < 2;} // The node is low on children making it impossible to merge two sibling children
boolean hasLeavesForChildren() // The node has leaves for children
{z(); assertBranch();
return node(tempNode, Branch.lastElement1().data).isLeaf();
}
int top() // The top next element of a branch
{z(); assertBranch();
final int s = branchSize();
return Branch.elementAt1(s).data;
}
public String toString() // Print a node
{final StringBuilder s = new StringBuilder();
if (isLeaf()) // Print a leaf
{s.append("Leaf(node:"+node+" size:"+leafSize()+")\n");
final int N = leafSize(); // Number of elements in leaf
for (int i = 0; i < N; i++) // Each element in the leaf
{final StuckSML.ElementAt kd = Leaf.elementAt1(i);
s.append(" "+(i+1)+" key:"+kd.key+" data:"+kd.data+"\n");
}
}
else // Print a branch
{s.append("Branch(node:"+node+
" size:"+branchSize()+
" top:"+top()+"\n");
final int N = Branch.size()-1; // Number of elements in branch not including top
for (int i = 0; i < N; i++)
{final StuckSML.ElementAt kn = Branch.elementAt1(i);
s.append(String.format(" %2d key:%2d next:%2d\n", i+1, kn.key, kn.data));
}
final StuckSML.ElementAt kn = Branch.elementAt1(N);
s.append(" Top:"+kn.data+")\n");
}
return s.toString();
}
//D2 Search // Search within a node
class FindEqualInLeaf // Find the first key in the leaf that is equal to the search key
{Node leaf; // The leaf being searched
int search; // Search key
boolean found; // Whether the key was found
int data; // Data associated with the key
int index; // Index of first such key if found
int base; // Base of the leaf
FindEqualInLeaf() {} // Create finder
FindEqualInLeaf findEqualInLeaf(int Search) // Find the first key in the leaf that is equal to the search key
{z(); assertLeaf();
leaf = Node.this;
search = Search;
base = leafBase();
final StuckSML.Search s = Leaf.search1(Search);
found = s.found;
index = s.index;
data = s.data;
return this;
}
public String toString() // Print details of find equal in leaf
{final StringBuilder s = new StringBuilder();
s.append("FindEqualInLeaf(Leaf:"+leaf.node);
s.append(" Key:"+search+" found:"+found);
if (found) s.append(" data:"+data+" index:"+index);
s.append(")\n");
return s.toString();
}
}
final FindEqualInLeaf FindEqualInLeaf1 = new FindEqualInLeaf();
FindEqualInLeaf findEqualInLeaf1(int Search) {z(); return FindEqualInLeaf1.findEqualInLeaf(Search);}
class FindFirstGreaterThanOrEqualInLeaf // Find the first key in the leaf that is equal to or greater than the search key
{Node leaf; // The leaf being searched
int search; // Search key
boolean found; // Whether the key was found
int first; // Index of first such key if found
int base; // Base of the leaf
FindFirstGreaterThanOrEqualInLeaf // Find the first key in the leaf that is equal to or greater than the search key
findFirstGreaterThanOrEqualInLeaf(int Search) // Find the first key in the leaf that is equal to or greater than the search key
{z(); assertLeaf();
leaf = Node.this;
search = Search;
base = leafBase();
final StuckSML.SearchFirstGreaterThanOrEqual s =
Leaf.searchFirstGreaterThanOrEqual1(Search);
found = s.found;
first = s.index;
return this;
}
public String toString() // Print results of search
{final StringBuilder s = new StringBuilder();
s.append("FindFirstGreaterThanOrEqualInLeaf(Leaf:"+leaf.node);
s.append(" Key:"+search+" found:"+found);
if (found) s.append(" first:"+first);
s.append(")\n");
return s.toString();
}
}
final FindFirstGreaterThanOrEqualInLeaf FindFirstGreaterThanOrEqualInLeaf1 = new FindFirstGreaterThanOrEqualInLeaf();
FindFirstGreaterThanOrEqualInLeaf findFirstGreaterThanOrEqualInLeaf1(int Search) {z(); return FindFirstGreaterThanOrEqualInLeaf1.findFirstGreaterThanOrEqualInLeaf(Search);}
class FindFirstGreaterThanOrEqualInBranch // Find the first key in the branch that is equal to or greater than the search key
{Node branch; // The branch being searched
int search; // Search key
boolean found; // Whether the key was found
int first; // Index of first such key if found
int next; // The corresponding next field or top if no such key was found
int base; // Base of the branch
FindFirstGreaterThanOrEqualInBranch // Find the first key in the branch that is equal to or greater than the search key
findFirstGreaterThanOrEqualInBranch(int Search) // Find the first key in the branch that is equal to or greater than the search key
{z(); assertBranch();
branch = Node.this;
search = Search;
base = branchBase();
final StuckSML.SearchFirstGreaterThanOrEqualExceptLast s =
Branch.searchFirstGreaterThanOrEqualExceptLast1(Search);
found = s.found;
first = s.index;
next = s.found ? s.data : Branch.lastElement1().data; // Next if no key matches
return this;
}
public String toString() // Print search results
{final StringBuilder s = new StringBuilder();
s.append("FindFirstGreaterThanOrEqualInBranch(branch:"+branch.node);
s.append(" Key:"+search+" found:"+found+" next:"+next);
if (found) s.append(" first:"+first);
s.append(")\n");
return s.toString();
}
}
final FindFirstGreaterThanOrEqualInBranch FindFirstGreaterThanOrEqualInBranch1 = new FindFirstGreaterThanOrEqualInBranch();
FindFirstGreaterThanOrEqualInBranch findFirstGreaterThanOrEqualInBranch1(int Search) {z(); return FindFirstGreaterThanOrEqualInBranch1.findFirstGreaterThanOrEqualInBranch(Search);}
//D2 Array // Represent the contents of the tree as an array
void leafToArray(Stack<StuckSML.ElementAt>s) // Leaf as an array
{z(); assertLeaf();
final int K = leafSize();
for (int i = 0; i < K; i++)
{z();
final StuckSML.ElementAt e = Leaf.elementAt1(i), E = e.copy();
s.push(E);
}
}
void branchToArray(Stack<StuckSML.ElementAt>s) // Branch to array
{z(); assertBranch();
final int K = Branch.size(); // Include top next
if (K > 0) // Branch has key, next pairs
{z();
for (int i = 0; i < K; i++)
{z();
final int next = Branch.elementAt1(i).data; // Each key, next pair
final Node n = node(new Node(), next); // Using recursion here is unsatisfactory.
if (n.isLeaf()) {z(); n.leafToArray(s);}
else
{z();
if (next == 0)
{say("Cannot descend through root from index", i,
"in branch", node);
break;
}
z(); n.branchToArray(s);
}
}
}
}
//D2 Print // Print the contents of the tree
void printLeaf(Stack<StringBuilder>S, int level) // Print leaf horizontally
{assertLeaf();
padStrings(S, level);
final StringBuilder s = new StringBuilder(); // String builder
final int K = leafSize();
for (int i = 0; i < K; i++)
{s.append(""+Leaf.elementAt1(i).key+",");
}
if (s.length() > 0) s.setLength(s.length()-1); // Remove trailing comma if present
s.append("="+node+" ");
S.elementAt(level*linesToPrintABranch).append(s.toString());
padStrings(S, level);
}
void printBranch(Stack<StringBuilder>S, int level) // Print branch horizontally
{assertBranch();
if (level > maxPrintLevels) return;
padStrings(S, level);
final int L = level * linesToPrintABranch;
final int K = branchSize();
if (K > 0) // Branch has key, next pairs
{for (int i = 0; i < K; i++)
{final int next = Branch.elementAt1(i).data; // Each key, next pair
final Node n = node(new Node(), next); // printing will not be part of the chip so we can use recursionand create new nodes as needed
if (n.isLeaf())
{n.printLeaf(S, level+1);
}
else
{if (next == 0)
{say("Cannot descend through root from index", i,
"in branch", node);
break;
}
n.printBranch(S, level+1);
}
S.elementAt(L+0).append(""+Branch.elementAt1(i).key); // Key
S.elementAt(L+1).append(""+node+(i > 0 ? "."+i : "")); // Branch,key, next pair
S.elementAt(L+2).append(""+Branch.elementAt1(i).data);
}
}
else // Branch is empty so print just the index of the branch
{S.elementAt(L+0).append(""+node+"Empty");
}
final int top = top(); // Top next will always be present
S.elementAt(L+3).append(top); // Append top next
final Node n = node(new Node(), top);
if (n.isLeaf()) // Print leaf
{n.printLeaf(S, level+1);
}
else // Print branch
{if (top == 0)
{say("Cannot descend through root from top in branch:", node);
return;
}
n.printBranch(S, level+1);
}
padStrings(S, level);
}
//D2 Split // Split nodes in half to increase the number of nodes in the tree
void splitLeafRoot() // Split a leaf which happens to be a full root into two half full leaves while transforming the root leaf into a branch
{z(); assertLeaf();
z(); if (node != 0) stop("Wanted root, but got node:", node);
z(); if (!isFull()) stop("Root is not full, but has size:", leafSize());
final Node l = allocLeaf(leftNode); // New left leaf
final Node r = allocLeaf(rightNode); // New right leaf
final Node p = this; // Root is the parent
final int sl = splitLeafSize();
for (int i = 0; i < sl; i++) // Build left leaf from parent
{z();
final StuckSML.Shift f = p.Leaf.shift1();
l.Leaf.push(f.key, f.data);
}
for (int i = 0; i < sl; i++) // Build right leaf from parent
{z();
final StuckSML.Shift f = p.Leaf.shift1();
r.Leaf.push(f.key, f.data);
}
final int first = r.Leaf.firstElement1().key; // First of right leaf
final int last = l.Leaf. lastElement1().key; // Last of left leaf
final int kv = (last + first) / 2; // Mid key
setBranch();
p.Branch.clear(); // Clear the branch
p.Branch.push (kv, l.node); // Insert left leaf into root
p.Branch.push (0, r.node); // Insert right into root. This will be the top node and so ignored by search ... except last.
}
void splitBranchRoot() // Split a branch which happens to be a full root into two half full branches while retaining the current branch as the root
{z(); assertBranch();
z(); if (node != 0) stop("Not root, but node:", node);
z(); if (!isFull()) stop("Root is not full, but has size:", branchSize());
z();
final Node l = allocBranch(leftNode); // New left branch
final Node r = allocBranch(rightNode); // New right branch
final Node p = this; // Root is the parent
final int sb = splitBranchSize(); // Branch split size
for (int i = 0; i < sb; i++) // Build left child from parent
{z();
final StuckSML.Shift f = p.Branch.shift1();
l.Branch.push(f.key, f.data);
}
final StuckSML.Shift pl = Branch.shift2(); // This key, next pair will be part of the root
l.Branch.push(0, pl.data); // Becomes top and so ignored by search ... except last
for(int i = 0; i < sb; i++) // Build right child from parent
{z();
final StuckSML.Shift f = p.Branch.shift1();
r.Branch.push(f.key, f.data);
}
final StuckSML.Shift pr = Branch.shift3(); // Top of root
r.Branch.push(0, pr.data); // Becomes top and so ignored by search ... except last
p.Branch.clear(); // Refer to new branches from root
p.Branch.push (pl.key, l.node);
p.Branch.push (0, r.node); // Becomes top and so ignored by search ... except last
}
void splitLeaf(Node parent, int index) // Split a leaf which is not the root
{z(); assertLeaf();
z(); if (node == 0) stop("Cannot split root with this method");
z(); final int S = leafSize(), I = index;
z(); final boolean nif = !isFull(), pif = parent.isFull();
z(); if (nif) stop("Leaf:", node, "is not full, but has:", S, this);
z(); if (pif) stop("Parent:", parent, "must not be full");
z(); if (I < 0) stop("Index", I, "too small");
z(); if (I > S) stop("Index", I, "too big for leaf with:", S);
z();
final Node p = parent; // Parent
final Node l = allocLeaf(leftNode); // New split out leaf
final Node r = this; // Existing leaf
final int sl = splitLeafSize();
for (int i = 0; i < sl; i++) // Build left leaf
{z();
final StuckSML.Shift f = r.Leaf.shift1();
l.Leaf.push(f.key, f.data);
}
final int F = r.Leaf.firstElement1().key;
final int L = l.Leaf. lastElement1().key;
final int splitKey = (F + L) / 2;
p.Branch.insertElementAt(splitKey, l.node, index); // Insert new key, next pair in parent
}
void splitBranch(Node parent, int index) // Split a branch which is not the root by splitting right to left
{z(); assertBranch();
z(); final int bs = branchSize(), I = index, pn = parent.node, nd = node;
z(); final boolean nif = !isFull(), pif = parent.isFull();
z(); if (nd == 0) stop("Cannot split root with this method");
z(); if (nif) stop("Branch:", nd, "is not full, but", bs);
z(); if (pif) stop("Parent:", pn, "must not be full");
z(); if (I < 0) stop("Index", I, "too small in node:", nd);
z(); if (I > bs) stop("Index", I, "too big for branch with:",
bs, "in node:", nd);
z();
final Node p = parent;
final Node l = allocBranch(leftNode);
final Node r = this;
final int pb = parent.branchBase(),
lb = l.branchBase(), rb = r.branchBase();
final int sb = splitBranchSize();
for (int i = 0; i < sb; i++) // Build left branch from right
{z(); final StuckSML.Shift f = r.Branch.shift1();
l.Branch.push(f.key, f.data);
}
final StuckSML.Shift split = r.Branch.shift1(); // Build right branch
l.Branch.push (0, split.data); // Becomes top and so is ignored by search ... except last
p.Branch.insertElementAt(split.key, l.node, index);
}
boolean stealFromLeft(int index) // Steal from the left sibling of the indicated child if possible to give to the right - Dennis Moore, Dennis Moore, Dennis Moore.
{z(); assertBranch();
z(); if (index == 0) return false;
z(); if (index < 0) stop("Index", index, "too small");
z(); if (index > branchSize()) stop("Index", index, "too big");
z();
final Node P = this;
final StuckSML.ElementAt L = P.Branch.elementAt1(index-1);
final StuckSML.ElementAt R = P.Branch.elementAt2(index+0);
if (hasLeavesForChildren()) // Children are leaves
{z();
final Node l = node( leftNode,L.data);
final Node r = node(rightNode,R.data);
final int nl = l.leafSize();
final int nr = r.leafSize();
z(); if (nr >= maxKeysPerLeaf()) return false; // Steal not possible because there is no where to put the steal
z(); if (nl <= 1) return false; // Steal not allowed because it would leave the leaf sibling empty
z();
final StuckSML.LastElement le = l.Leaf.lastElement1();
r.Leaf.insertElementAt(le.key, le.data, 0); // Increase right
l.Leaf.pop(); // Reduce left
final int lk = l.Leaf.elementAt1(nl-2).key; // Last key on left
P.Branch.setElementAt(lk, L.data, index-1); // Swap key of parent
}
else // Children are branches
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.branchSize();
final int nr = r.branchSize();
z(); if (nr >= maxKeysPerBranch()) return false; // Steal not possible because there is no where to put the steal
z(); if (nl <= 1) return false; // Steal not allowed because it would leave the left sibling empty
z();
final StuckSML.LastElement t = l.Branch.lastElement1(); // Increase right with left top
final int key = P.Branch.elementAt1(index).key; // Top key
r.Branch.insertElementAt(key, t.data, 0); // Increase right with left top
l.Branch.pop(); // Remove left top
final StuckSML.FirstElement b = r.Branch.firstElement1(); // Increase right with left top
final int pk = P.Branch.elementAt1(index-1).key; // Parent key
r.Branch.setElementAt (pk, b.data, 0); // Reduce key of parent of right
final int lk = l.Branch.lastElement1().key; // Last left key
P.Branch.setElementAt(lk, L.data, index-1); // Reduce key of parent of left
}
return true;
}
boolean stealFromRight(int index) // Steal from the right sibling of the indicated child if possible
{z(); assertBranch();
z(); if (index == branchSize()) return false;
z(); if (index < 0) stop("Index", index, "too small");
z(); if (index >= branchSize()) stop("Index", index, "too big");
z();
final Node P = this;
final StuckSML.ElementAt L = P.Branch.elementAt1(index+0);
final StuckSML.ElementAt R = P.Branch.elementAt2(index+1);
if (hasLeavesForChildren()) // Children are leaves
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.leafSize();
final int nr = r.leafSize();
z(); if (nl >= maxKeysPerLeaf()) return false; // Steal not possible because there is no where to put the steal
z(); if (nr <= 1) return false; // Steal not allowed because it would leave the right sibling empty
z();
final StuckSML.FirstElement f = r.Leaf.firstElement1(); // First element of right child
l.Leaf.push (f.key, f.data); // Increase left
P.Branch.setElementAt (f.key, L.data, index); // Swap key of parent
r.Leaf.removeElementAt1(0); // Reduce right
}
else // Children are branches
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.branchSize();
final int nr = r.branchSize();
z(); if (nl >= maxKeysPerBranch()) return false; // Steal not possible because there is no where to put the steal
z(); if (nr <= 1) return false; // Steal not allowed because it would leave the right sibling empty
z();
final StuckSML.LastElement le = l.Branch.lastElement1(); // Last element of left child
l.Branch.setElementAt(L.key, le.data, nl); // Left top becomes real
final StuckSML.FirstElement fe = r.Branch.firstElement1(); // First element of right child
l.Branch.push(0, fe.data); // New top for left is ignored by search ,.. except last
P.Branch.setElementAt(fe.key, L.data, index); // Swap key of parent
r.Branch.removeElementAt1(0); // Reduce right
}
return true;
}
//D2 Merge // Merge two nodes together and free the resulting free node
boolean mergeRoot() // Merge into the root
{z();
z(); if (root.isLeaf() || branchSize() > 1) return false;
z(); if (node != 0) stop("Expected root, got:", node);
z();
final Node p = this;
final Node l = node( leftNode, p.Branch.firstElement1().data);
final Node r = node(rightNode, p.Branch. lastElement1().data);
if (hasLeavesForChildren()) // Leaves
{z();
if (l.leafSize() + r.leafSize() <= maxKeysPerLeaf())
{z(); p.Leaf.clear();
final int nl = l.leafSize();
for (int i = 0; i < nl; ++i)
{z();
final StuckSML.Shift f = l.Leaf.shift1();
p.Leaf.push(f.key, f.data);
}
final int nr = r.leafSize();
for (int i = 0; i < nr; ++i)
{z();
final StuckSML.Shift f = r.Leaf.shift1();
p.Leaf.push(f.key, f.data);
}
setLeaf();
l.free();
r.free();
return true;
}
}
else if (l.branchSize() + 1 + r.branchSize() <= maxKeysPerBranch()) // Branches
{z();
final StuckSML.FirstElement pkn = p.Branch.firstElement1();
p.Branch.clear();
final int nl = l.branchSize();
for (int i = 0; i < nl; ++i)
{z();
final StuckSML.Shift f = l.Branch.shift1();
p.Branch.push(f.key, f.data);
}
final int data = l.Branch.lastElement1().data;
p.Branch.push(pkn.key, data);
final int nr = r.branchSize();
for (int i = 0; i < nr; ++i)
{z();
final StuckSML.Shift f = r.Branch.shift1();
p.Branch.push(f.key, f.data);
}
final int Data = r.Branch.lastElement2().data; // Top next
p.Branch.push(0, Data); // Top so ignored by search ... except last
l.free();
r.free();
return true;
}
z();
return false;
}
boolean mergeLeftSibling(int index) // Merge the left sibling
{z(); assertBranch();
z(); if (index == 0) return false;
final int bs = branchSize();
final String bss = "for branch of size:";
z(); if (index < 0 ) stop("Index", index, "too small", bss, bs);
z(); if (index > bs) stop("Index", index, "too big", bss, bs);
//if (branchSize() < 2) stop("Node:", this, "must have two or more children");
z(); if (bs < 2 ) return false;
z();
final Node p = this;
final StuckSML.ElementAt L = p.Branch.elementAt1(index-1);
final StuckSML.ElementAt R = p.Branch.elementAt2(index-0);
if (hasLeavesForChildren()) // Children are leaves
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.leafSize();
final int nr = r.leafSize();
if (nl + nr >= maxKeysPerLeaf()) return false; // Combined body would be too big
z();
final int N = l.Leaf.size(); // Number of entries to remove
for (int i = 0; i < N; i++) // Transfer left to right
{z(); final StuckSML.Pop q = l.Leaf.pop();
r.Leaf.insertElementAt(q.key, q.data, 0);
}
l.free(); // Free the empty left node
}
else // Children are branches
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.branchSize();
final int nr = r.branchSize();
if (nl + 1 + nr > maxKeysPerBranch()) return false; // Merge not possible because there is not enough room for the combined result
z();
final int t = p.Branch.elementAt1(index-1).key; // Top key
final StuckSML.LastElement le = l.Branch.lastElement1(); // Last element of left child
r.Branch.insertElementAt(t, le.data, 0); // Left top to right
l.Branch.pop(); // Remove left top
final int N = l.Branch.size(); // Number of entries to remove
for (int i = 0; i < N; i++) // Transfer left to right
{z();
final StuckSML.Pop q = l.Branch.pop();
r.Branch.insertElementAt(q.key, q.data, 0);
}
l.free(); // Free the empty left node
}
p.Branch.removeElementAt1(index-1); // Reduce parent on left
return true;
}
boolean mergeRightSibling(int index) // Merge the right sibling
{z(); assertBranch();
final int bs = branchSize();
final String bss = "for branch of size:";
z(); if (index >= bs) return false;
z(); if (index < 0 ) stop("Index", index, "too small", bss, bs);
z(); if (index > bs) stop("Index", index, "too big", bss, bs);
//if (branchSize() < 2) stop("Node:", this, "must have two or more children");
z(); if (bs < 2) return false;
z();
final Node p = this;
final StuckSML.ElementAt L = p.Branch.elementAt1(index+0);
final StuckSML.ElementAt R = p.Branch.elementAt2(index+1);
if (hasLeavesForChildren()) // Children are leaves
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.leafSize();
final int nr = r.leafSize();
if (nl + nr > maxKeysPerLeaf()) return false; // Combined body would be too big for one leaf
z();
final int N = r.Leaf.size(); // Number of entries to remove
for (int i = 0; i < N; i++) // Transfer right to left
{z();
final StuckSML.Shift q = r.Leaf.shift1();
l.Leaf.push(q.key, q.data);
}
r.free(); // Free the empty right node
}
else // Children are branches
{z();
final Node l = node( leftNode, L.data);
final Node r = node(rightNode, R.data);
final int nl = l.branchSize();
final int nr = r.branchSize();
if (nl + 1 + nr > maxKeysPerBranch()) return false; // Merge not possible because there is not enough room in a single branch
z(); final StuckSML.LastElement le = l.Branch.lastElement1(); // Last element of left child
z(); final StuckSML.ElementAt ea = p.Branch.elementAt1(index); // Parent dividing element
l.Branch.setElementAt(ea.key, le.data, nl); // Re-key left top
final int N = r.Branch.size(); // Number of entries to remove
for (int i = 0; i < N; i++) // Transfer right to left
{z(); final StuckSML.Shift f = r.Branch.shift1();
l.Branch.push(f.key, f.data);
}
r.free(); // Free the empty right node
}
final StuckSML.ElementAt pkn = p.Branch.elementAt1(index+1); // One up from dividing point in parent
final StuckSML.ElementAt dkn = p.Branch.elementAt2(index); // Dividing point in parent
p.Branch.setElementAt(pkn.key, dkn.data, index); // Install key of right sibling in this child
p.Branch.removeElementAt1(index+1); // Reduce parent on right
return true;
}
//D2 Balance // Balance the tree by merging and stealing
void balance(int index) // Augment the indexed child so it has at least two children in its body
{z(); assertBranch();
z(); if (index < 0) stop("Index", index, "too small");
z(); if (index > branchSize()) stop("Index", index, "too big");
z(); if (isLow() && node != root.node)
{stop("Parent:", node, "must not be low on children");
}
z();
final StuckSML.ElementAt p = Branch.elementAt1(index);
z(); if (!node(tempNode, p.data).isLow()) return;
z(); if (stealFromLeft (index)) return;
z(); if (stealFromRight (index)) return;
z(); if (mergeLeftSibling (index)) return;
z(); if (mergeRightSibling(index)) return;
stop("Unable to balance child:", p.data);
}
} // Node
Node node(Node Node, int node) // Refer to a node by number
{Node.node = node;
Node.setStucks();
return Node;
}
//D1 Array // Key, data pairs in the tree as an array
Stack<StuckSML.ElementAt> toArray() // Key, data pairs in the tree as an array
{z();
final Stack<StuckSML.ElementAt> s = new Stack<>();
if (root.isLeaf()) {z(); root. leafToArray(s);}
else {z(); root.branchToArray(s);}
return s;
}
//D1 Print // Print a BTree horizontally
String printBoxed() // Print a tree in a box
{final String s = toString();
final int n = longestLine(s)-1;
final String[]L = s.split("\n");
final StringBuilder t = new StringBuilder();
t.append("+"); t.append("-".repeat(n)); t.append("+\n");
for(String l : L) t.append("| "+l+"\n");
t.append("+"); t.append("-".repeat(n)); t.append("+\n");
return t.toString();
}
void padStrings(Stack<StringBuilder> S, int level) // Pad the strings at each level of the tree so we have a vertical face to continue with - a bit like Marc Brunel's tunneling shield
{final int N = level * linesToPrintABranch + maxKeysPerLeaf(); // Number of lines we might want
for (int i = S.size(); i <= N; ++i) S.push(new StringBuilder()); // Make sure we have a full deck of strings
int m = 0; // Maximum length
for (StringBuilder s : S) m = m < s.length() ? s.length() : m; // Find maximum length
for (StringBuilder s : S) // Pad each string to maximum length
{if (s.length() < m) s.append(" ".repeat(m - s.length())); // Pad string to maximum length
}
}
String printCollapsed(Stack<StringBuilder> S) // Collapse horizontal representation into a string
{z();
final StringBuilder t = new StringBuilder(); // Print the lines of the tree that are not blank
for (StringBuilder s : S)
{z();
final String l = s.toString();
if (l.isBlank()) continue;
t.append(l+"|\n");
}
return t.toString();
}
String print() // Print a tree horizontally
{z();
final Stack<StringBuilder> S = new Stack<>();
if (root.isLeaf())
{z();
root.printLeaf(S, 0);
}
else
{z();
root.printBranch(S, 0);
}
return printCollapsed(S);
}
//D1 Find // Find the data associated with a key
class Find // Find the data associated with a key in the tree
{Node.FindEqualInLeaf search; // Details of the search of the containing leaf
Find find(int Key) // Find the data associated with a key in the tree
{z();
if (root.isLeaf()) // The root is a leaf
{z();
search = root.findEqualInLeaf1(Key);
return this;
}
Node parent = root; // Parent starts at root which is known to be a branch
for (int i = 0; i < maxDepth; i++) // Step down through tree
{z();
final Node.FindFirstGreaterThanOrEqualInBranch down = // Find next child in search path of key
parent.findFirstGreaterThanOrEqualInBranch1(Key);
final Node n = node(findNode, down.next);
if (n.isLeaf()) // Found the containing search
{z();
search = n.findEqualInLeaf1(Key);
return this;
}
parent = node(parentNode, n.node); // Step down to lower branch
}
stop("Search did not terminate in a leaf");
return this;
}
Node leaf() {z(); return search.leaf;}
boolean found() {z(); return search.found;}
int index() {z(); return search.index;}
int data() {z(); return search.data;}
public String toString() // Print find result
{final StringBuilder s = new StringBuilder();
s.append("Find(search:"+search);
s.append( " search:"+index());
if (found())
{s.append( " data:"+data());
s.append(" index:"+index());
}
s.append(")\n");
return s.toString();
}