/** * Split function. Find the middle element 'mid'. And split the NodeArray using 'mid'. Copy the * split array into a new Node 'newNode' of type 'Btree'. Insert corresponding child elements with * it Update keycount and childcount * * @param i */ private void split(int i) { if ((childArray[i].keycount) % 2 != 0) { int x1 = childArray[i].keycount / 2; int x2 = childArray[i].childcount / 2; int mid = childArray[i].keyArray[childArray[i].keycount / 2]; // Split the node at mid int midv = childArray[i].valueArray[childArray[i].keycount / 2]; BTree splitNode = new BTree(max); // New node created to store split data for (int j = x1 + 1; j <= 2 * x1; j++) splitNode.keyArray[j - x1 - 1] = childArray[i].keyArray[j]; for (int j = x1 + 1; j <= 2 * x1; j++) splitNode.valueArray[j - x1 - 1] = childArray[i].valueArray[j]; for (int j = x2; j < 2 * x2; j++) splitNode.childArray[j - x2] = childArray[i].childArray[j]; // Copy it's respective childArray childArray[i].keycount = x1; // Update Values' count of original child childArray[i].childcount = x2; // Update it's child count splitNode.keycount = x1; // Set new node's value count splitNode.childcount = x2; // Set new node's child count int temp = scanKeyArray(mid); // Insert the 'mid' node into it's parent insertKey(temp, mid, midv); insertChild(i + 1, splitNode); } }
/** * The Basic Insert function. This funcyion insert the value in the tree. If the NodeArray is * full, then it splits the NodeArray by calling the split function. * * @param value */ public void BTreeInsert(int key, int value) { preInsert(key, value); // Simple insert if (keycount > max) // Check if it has max values { BTree newNode = new BTree(max); newNode.keycount = keycount; newNode.childcount = childcount; System.arraycopy(this.valueArray, 0, newNode.valueArray, 0, keycount); System.arraycopy(this.keyArray, 0, newNode.keyArray, 0, keycount); System.arraycopy(this.childArray, 0, newNode.childArray, 0, childcount); this.keycount = 0; this.childcount = 1; childArray[0] = newNode; split(0); } }