algoritmauzmanı
Sign in
TREN
7.2Heap with Linked Nodes
Lesson 7.2.4

Building a heap from values

When building a heap with an array, the values were copied as they were, then every node from the last inner node up to the root was sifted down. The linked structure has the same two phases. The difference is that each node has to be created and linked to its parent, and reaching node k means walking down the tree.

What you will learn
  • How to put values into nodes without ordering them and link them as a complete tree
  • How to sift down the inner nodes from count / 2 to 1
  • Why the linked build is O(n log n) rather than O(n)
7 minTime O(n log n)Memory O(n)C · Java · Python

1Idea

In the first phase a node is created for each value and linked as in insertion: count goes up by one, the parent is found with nodeAt(count / 2), an even position is a left child and an odd one a right child. The only difference is that sift up is not called. When the phase ends the shape of the tree is right, but the order does not follow the heap rule yet.

The second phase is the same as in the array version. Leaves have no children, so they are left alone. The last inner node is at position count / 2; the loop goes back from there to the root and sifts down each node. By the time a node's turn comes, the two subtrees below it are already heaps.

Because positions start at 1, the loop goes down from count / 2 to 1. In the array the indexes started at 0 and the loop went from n / 2 - 1 to 0: the same nodes, different numbers.

The code also works on a heap that is not empty. The new values are linked at the end, and the second phase goes over every inner node again; where the heap rule already holds, sift down stops at once.

The total work of the sift downs is O(n), as in the array. But every nodeAt call starts at the root and walks O(log n) steps, and it is called n times. So the linked version costs O(n log n) in total. Keeping the node pointers in a temporary array brings it down to O(n), but then you are leaning on an array again.

2Step by step

The values are 50, 30, 40, 10, 20, 15. The drawing starts at the end of the first phase: six nodes linked in order. Then nodes 3, 2 and 1 are sifted down.

3k2k1k501302403104205156153406102304101502202505rootnsmallest
  1. The first phase is done: the nodes are linked in the given order at positions 1 to 6. The shape is a complete tree, but 50 sits at the root.
  2. k = 3: the last inner node. 40's only child, 15, is smaller.
  3. 40 and 15 are swapped. Node 6 has no children: the sift ends.
  4. k = 2: 30's children are 10 and 20. The smaller, 10, is smaller than 30.
  5. 30 and 10 are swapped. Node 4 has no children: the sift ends.
  6. k = 1: the root holds 50 and its children are 10 and 15. The smaller is 10.
  7. 50 and 10 are swapped; n goes down to node 2. Its children are 30 and 20; the smaller, 20, is smaller than 50.
  8. 50 and 20 are swapped and the sift stops at leaf 5. The heap is ready: 10, 20, 15, 30, 50, 40.

struct HeapNode {    int data;    struct HeapNode* left;    struct HeapNode* right;    struct HeapNode* parent;}; struct Heap {    struct HeapNode* root;    int count;}; struct HeapNode* nodeAt(struct Heap* h, int k) {    if (k < 1 || k > h->count) return NULL;    int bit = 1;    while (bit * 2 <= k) bit *= 2;    struct HeapNode* n = h->root;    for (bit /= 2; bit > 0; bit /= 2) n = (k & bit) ? n->right : n->left;    return n;} void siftDown(struct HeapNode* n) {    while (n != NULL) {        struct HeapNode* smallest = n;        if (n->left != NULL && n->left->data < smallest->data) smallest = n->left;        if (n->right != NULL && n->right->data < smallest->data) smallest = n->right;        if (smallest == n) return;        // not larger than either child        int temp = n->data;               // swap the values        n->data = smallest->data;        smallest->data = temp;        n = smallest;    }} bool buildHeap(struct Heap* h, int values[], int n) {    for (int i = 0; i < n; i++) {        struct HeapNode* node = malloc(sizeof(struct HeapNode));        if (node == NULL) return false;            // out of memory        node->data = values[i];                    // place it as it is        node->left = NULL; node->right = NULL; node->parent = NULL;        h->count++;        if (h->count == 1) { h->root = node; continue; }        struct HeapNode* parent = nodeAt(h, h->count / 2);        node->parent = parent;        if (h->count % 2 == 0) parent->left = node;        else parent->right = node;    }    for (int k = h->count / 2; k >= 1; k--) {        siftDown(nodeAt(h, k));                    // from the last inner node up to the root    }    return true;}
class HeapNode {    int data;    HeapNode left, right, parent;    HeapNode(int data) { this.data = data; }} class LinkedHeap {    HeapNode root;    int count = 0;     HeapNode nodeAt(int k) {        if (k < 1 || k > count) return null;        int bit = 1;        while (bit * 2 <= k) bit *= 2;        HeapNode n = root;        for (bit /= 2; bit > 0; bit /= 2) n = (k & bit) != 0 ? n.right : n.left;        return n;    }     void siftDown(HeapNode n) {        while (n != null) {            HeapNode smallest = n;            if (n.left != null && n.left.data < smallest.data) smallest = n.left;            if (n.right != null && n.right.data < smallest.data) smallest = n.right;            if (smallest == n) return;        // not larger than either child            int temp = n.data;                // swap the values            n.data = smallest.data;            smallest.data = temp;            n = smallest;        }    }     void buildHeap(int[] values) {        for (int value : values) {            HeapNode node = new HeapNode(value);   // place it as it is            count++;            if (count == 1) { root = node; continue; }            HeapNode parent = nodeAt(count / 2);            node.parent = parent;            if (count % 2 == 0) parent.left = node;            else parent.right = node;        }        for (int k = count / 2; k >= 1; k--) {            siftDown(nodeAt(k));                   // from the last inner node up to the root        }    }}
class HeapNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None        self.parent = None class LinkedHeap:    def __init__(self):        self.root = None        self.count = 0     def node_at(self, k):        if k < 1 or k > self.count:            return None        bit = 1        while bit * 2 <= k:            bit *= 2        n = self.root        bit //= 2        while bit > 0:            n = n.right if k & bit else n.left            bit //= 2        return n     def sift_down(self, n):        while n is not None:            smallest = n            if n.left is not None and n.left.data < smallest.data:                smallest = n.left            if n.right is not None and n.right.data < smallest.data:                smallest = n.right            if smallest is n:                return  # not larger than either child            n.data, smallest.data = smallest.data, n.data  # swap the values            n = smallest     def build_heap(self, values):        for value in values:            node = HeapNode(value)  # place it as it is            self.count += 1            if self.count == 1:                self.root = node                continue            parent = self.node_at(self.count // 2)            node.parent = parent            if self.count % 2 == 0:                parent.left = node            else:                parent.right = node        for k in range(self.count // 2, 0, -1):            self.sift_down(self.node_at(k))  # from the last inner node up to the root

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n log n)

The sift downs add up to O(n). In both phases nodeAt is called for every node and each call takes O(log n). Total O(n log n).

Memory
O(n)

O(n) memory is allocated for n nodes. Beyond that, a few variables are enough.

The array version is O(n), because it reaches element k directly with items[k]. In the linked version, adding the values one by one with insert is O(n log n) too; but that way sifts up on every insertion, and this way does not.

4Common mistake

A common mistake is starting the loop at the root:

for (int k = 1; k <= h->count / 2; k++) {   // wrong direction    siftDown(nodeAt(h, k));}

When the root is sifted down, its subtrees are not heaps yet. For 50, 30, 40, 10, 20, 15 this loop leaves 30 at the root, although the smallest value is 10. Sift down only works when the subtrees are heaps; that is why the loop goes from the bottom up.

5Try it

A linked heap is given 9 values. In the second phase, which position is sifted down first?

Show the answer

The answer is A. The last inner node is at position 9 / 2 = 4. Nodes 5 to 9 are leaves and are left alone.

Why is building a linked heap not O(n)?

Show the answer

The answer is A. The sift downs add up to O(n), as in the array. The extra cost comes from nodeAt: it is called n times and walks O(log n) steps each time.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.