Skip to content
Laviyx Learn

Try

DS Lab · Experiment 13

B-tree insertion and search

CTreesJNTUH R22 · CS306PC

Aim

To write a C program that implements a B-tree of order 3 with insertion (including node splits) and search, and displays the tree level by level.

Algorithm

  1. A B-tree of order m: every node holds at most m − 1 keys in sorted order and has at most m children; all leaves are at the same level. Here m = 3, so a node holds 1 or 2 keys.
  2. Insert key: start at the root and move down. In each node, find the child whose range contains the key, until a leaf is reached. Insert the key into the leaf in sorted order.
  3. If the node now has m keys (too many), split it: the middle key moves up into the parent, the keys left of it stay in this node, and the keys right of it go into a new node that becomes the parent's next child.
  4. The key that moved up may make the parent too full too, so the split is repeated on the way back up.
  5. If the root splits, make a new root holding only the middle key. This is the only way the tree grows taller.
  6. Search key: in each node, compare the key with the node's keys. If it matches, it is found; otherwise go down into the correct child. If a leaf has no match, the key is not present.
  7. Display the tree level by level using a queue, then free all nodes.

Program

C
#include <stdio.h>
#include <stdlib.h>

#define ORDER 3                 /* maximum number of children */
#define MAX_KEYS (ORDER - 1)    /* maximum number of keys in a node */
#define MAX_INPUT 20

struct node {
    int nkeys;
    int keys[ORDER];            /* one extra slot holds a key just before a split */
    struct node *child[ORDER + 1];
    int leaf;                   /* 1 if the node has no children */
};

struct node *new_node(int leaf) {
    struct node *n = malloc(sizeof(struct node));
    if (n == NULL) {
        printf("Memory not available\n");
        exit(1);
    }
    n->nkeys = 0;
    n->leaf = leaf;
    for (int i = 0; i <= ORDER; i++) {
        n->child[i] = NULL;
    }
    return n;
}

void print_node(struct node *n) {
    printf("[");
    for (int i = 0; i < n->nkeys; i++) {
        printf(i == 0 ? "%d" : " %d", n->keys[i]);
    }
    printf("]");
}

/* Split an overfull node n. The middle key goes up through *up_key,
   and the keys to its right go into a new node returned through *right. */
void split(struct node *n, int *up_key, struct node **right) {
    int mid = n->nkeys / 2;
    struct node *r = new_node(n->leaf);

    printf("  Node ");
    print_node(n);
    printf(" is too full: split, %d moves up\n", n->keys[mid]);

    *up_key = n->keys[mid];
    for (int j = mid + 1; j < n->nkeys; j++) {
        r->keys[r->nkeys++] = n->keys[j];
    }
    if (!n->leaf) {
        for (int j = mid + 1; j <= n->nkeys; j++) {
            r->child[j - mid - 1] = n->child[j];
        }
    }
    n->nkeys = mid;
    *right = r;
}

/* Insert key into the subtree rooted at n.
   Returns 1 if n was split (the caller must take *up_key and *right). */
int insert_rec(struct node *n, int key, int *up_key, struct node **right) {
    int i;
    if (n->leaf) {
        i = n->nkeys - 1;
        while (i >= 0 && n->keys[i] > key) {    /* shift bigger keys right */
            n->keys[i + 1] = n->keys[i];
            i--;
        }
        n->keys[i + 1] = key;
        n->nkeys++;
    } else {
        int pos = 0;
        while (pos < n->nkeys && key > n->keys[pos]) {
            pos++;
        }
        int mid_key = 0;
        struct node *new_child = NULL;
        if (!insert_rec(n->child[pos], key, &mid_key, &new_child)) {
            return 0;                           /* child did not split */
        }
        /* the child split: put mid_key at pos and new_child after it */
        for (i = n->nkeys; i > pos; i--) {
            n->keys[i] = n->keys[i - 1];
            n->child[i + 1] = n->child[i];
        }
        n->keys[pos] = mid_key;
        n->child[pos + 1] = new_child;
        n->nkeys++;
    }
    if (n->nkeys <= MAX_KEYS) {
        return 0;
    }
    split(n, up_key, right);
    return 1;
}

int search(struct node *n, int key) {
    while (n != NULL) {
        int i = 0;
        while (i < n->nkeys && key > n->keys[i]) {
            i++;
        }
        if (i < n->nkeys && key == n->keys[i]) {
            return 1;
        }
        if (n->leaf) {
            return 0;
        }
        n = n->child[i];
    }
    return 0;
}

struct node *insert(struct node *root, int key) {
    printf("Insert %d\n", key);
    if (root == NULL) {
        root = new_node(1);
        root->keys[0] = key;
        root->nkeys = 1;
        return root;
    }
    if (search(root, key)) {
        printf("  %d is already in the tree, skipped\n", key);
        return root;
    }
    int up_key = 0;
    struct node *right = NULL;
    if (insert_rec(root, key, &up_key, &right)) {
        struct node *new_root = new_node(0);    /* the tree grows one level */
        new_root->keys[0] = up_key;
        new_root->nkeys = 1;
        new_root->child[0] = root;
        new_root->child[1] = right;
        printf("  New root [%d] created\n", up_key);
        return new_root;
    }
    return root;
}

/* Print the tree level by level using a queue */
void display(struct node *root) {
    struct node *queue[100];
    int level[100];
    int front = 0, rear = 0, current = -1;

    queue[rear] = root;
    level[rear++] = 0;
    while (front < rear) {
        struct node *n = queue[front];
        int lv = level[front++];
        if (lv != current) {
            printf(current == -1 ? "Level %d: " : "\nLevel %d: ", lv);
            current = lv;
        }
        print_node(n);
        printf(" ");
        if (!n->leaf) {
            for (int i = 0; i <= n->nkeys; i++) {
                queue[rear] = n->child[i];
                level[rear++] = lv + 1;
            }
        }
    }
    printf("\n");
}

void free_tree(struct node *n) {
    if (n == NULL) {
        return;
    }
    if (!n->leaf) {
        for (int i = 0; i <= n->nkeys; i++) {
            free_tree(n->child[i]);
        }
    }
    free(n);
}

int main(void) {
    struct node *root = NULL;
    int n, key;

    printf("Enter number of keys (1-%d): ", MAX_INPUT);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX_INPUT) {
        printf("Invalid number of keys\n");
        return 1;
    }
    printf("Enter %d keys: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &key) != 1) {
            printf("Invalid input\n");
            free_tree(root);
            return 1;
        }
        root = insert(root, key);
    }

    printf("\nB-tree of order %d:\n", ORDER);
    display(root);

    while (1) {
        printf("\nEnter key to search (-1 to stop): ");
        if (scanf("%d", &key) != 1 || key == -1) {
            break;
        }
        printf("%d is %s\n", key, search(root, key) ? "found" : "not found");
    }

    free_tree(root);
    return 0;
}

Output

Output
Enter number of keys (1-20): 8
Enter 8 keys: 10 20 5 6 12 30 7 17
Insert 10
Insert 20
Insert 5
  Node [5 10 20] is too full: split, 10 moves up
  New root [10] created
Insert 6
Insert 12
Insert 30
  Node [12 20 30] is too full: split, 20 moves up
Insert 7
  Node [5 6 7] is too full: split, 6 moves up
  Node [6 10 20] is too full: split, 10 moves up
  New root [10] created
Insert 17

B-tree of order 3:
Level 0: [10] 
Level 1: [6] [20] 
Level 2: [5] [7] [12 17] [30] 

Enter key to search (-1 to stop): 17
17 is found

Enter key to search (-1 to stop): 8
8 is not found

Enter key to search (-1 to stop): -1

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Checking the run by hand: 10 and 20 fit in the root. Inserting 5 makes [5 10 20], which splits and sends 10 up as a new root. 30 makes the leaf [12 20 30] split, and 20 joins the root. Inserting 7 makes [5 6 7] split; 6 moves up and makes the root [6 10 20] too full, so the root splits too and 10 becomes the new root. The final tree is:

Text
            [10]
          /      \
       [6]        [20]
      /   \      /    \
    [5]   [7] [12 17] [30]

The program covers insertion and search. Deletion from a B-tree (borrowing keys from a sibling or merging nodes) is longer and is not included. Change ORDER to 4 or 5 to see wider nodes; the code works for any order of 3 or more.

Common mistakes

  • Splitting a node when it has m − 1 keys instead of m keys. A node of order m may hold m − 1 keys; it splits only when one more key arrives.

  • Forgetting to move the children along with the keys when an internal node splits, which disconnects part of the tree.

  • Growing the tree by adding a level at the bottom. A B-tree grows only at the top, when the root splits, which keeps all leaves at the same level.

  • Not shifting the parent's keys and child pointers to the right before placing the key that moved up.

Viva questions

Try to answer each one aloud before you open it.

  • What is a B-tree of order m?

    A balanced search tree where each node has at most m children and m − 1 keys, every node except the root has at least ⌈m/2⌉ children (unless it is a leaf), the root has at least two children if it is not a leaf, and all leaves are at the same level.

  • Why are B-trees used in databases and file systems?

    Each node holds many keys, so the tree is very short. Reading one node is one disk read, so finding a key needs only a few disk reads even for millions of keys.

  • When does the height of a B-tree increase?

    Only when the root splits. Then a new root is created above it, so all leaves stay at the same depth.

  • What is the time complexity of searching a B-tree?

    O(log n), because the height is O(log n) and the work inside each node is bounded by the order m.

  • What happens to the middle key when a node splits?

    It moves up into the parent. The keys smaller than it stay in the old node and the larger ones go to the new node.

Learn the concepts

All Data Structures Lab experiments →