void BTree::insert(int k) { if (root == NULL) { root = new BTreeNode(t, true); root->keys[0] = k; root->n = 1; } else { if (root->n == 2*t-1) { BTreeNode *s = new BTreeNode(t, false); s->C[0] = root; s->splitChild(0, root); int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); root = s; } else root->insertNonFull(k); } }
// The main function that inserts a new key in this B-Tree void BTree::insert(int k) { char varnam[64]; // If tree is empty if (root == NULL) { bzero(varnam, 64); sprintf(varnam,"%d",count); strcat(varnam,"node"); varnam[64]=0; // Allocate memory for root root =(BTreeNode *)nvalloc_(sizeof(BTreeNode), varnam, 0); //root = (BTreeNode *)nvalloc_(sizeof(BTreeNode)); root->Initialize(root, t, true, count); //root = new BTreeNode(t, true); root->keys[0] = k; // Insert key root->n = 1; // Update number of keys in root } else // If tree is not empty { // If root is full, then tree grows in height if (root->n == 2*t-1) { bzero(varnam, 64); sprintf(varnam,"%d",count); strcat(varnam,"node"); varnam[64]=0; // Allocate memory for root BTreeNode *s =(BTreeNode *)nvalloc_(sizeof(BTreeNode), varnam, 0); s->Initialize(s, t, false, count); // Allocate memory for new root //BTreeNode *s = new BTreeNode(t, false); BEGIN_OBJTRANS((void *)s,0); // Make old root as child of new root s->C[0] = root; // Split the old root and move 1 key to the new root s->splitChild(0, root); // New root has two children now. Decide which of the // two children is going to have new key int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); nvcommitobj((void *)s,0); // Change root root = s; } else // If root is not full, call insertNonFull for root root->insertNonFull(k); } count++; }
void BTree::insert(int k) { // If tree is empty if (root == NULL) { // Allocate memory for root root = new BTreeNode(t, true); root->keys[0] = k; // Insert key root->n = 1; // Update number of keys in root } else // If tree is not empty { // If root is full, then tree grows in height if (root->n == 2 * t - 1) { // Allocate memory for new root BTreeNode *s = new BTreeNode(t, false); // Make old root as child of new root s->C[0] = root; // Split the old root and move 1 key to the new root s->splitChild(0, root); // New root has two children now. Decide which of the // two children is going to have new key int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); // Change root root = s; } else // If root is not full, call insertNonFull for root root->insertNonFull(k); } }