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

Array or linked nodes?

You have coded a heap in two ways: with an array and with linked nodes. Both versions offer the same operations and the tree has the same shape in both. This lesson shows where they differ: reaching node k, the time to build a heap, memory and real-world speed. By the end you will see why real libraries choose the array.

What you will learn
  • Where the operation times of the two heap codings part ways
  • The difference in memory per node and the effect of the cache
  • How the ready-made heaps in Java and Python are coded
5 min

1The same tree, two codings

In both versions the heap is a complete binary tree and the rule is the same: every node is smaller than or equal to its children. What changes is where the nodes live and how they find each other.

// With an array (7.1)struct Heap {    int items[CAPACITY];   // the children of i are 2i + 1 and 2i + 2    int count;}; // With linked nodes (7.2)struct HeapNode {    int data;    struct HeapNode* left;    struct HeapNode* right;    struct HeapNode* parent;};struct Heap {    struct HeapNode* root;    int count;             // needed to find the last position};

In the array, the parent and children are a calculation: (i - 1) / 2, 2i + 1, 2i + 2. In the linked structure three pointers take their place. But the linked structure cannot know one thing by itself: where is the last node, and where is the next empty spot? For that it keeps count, and nodeAt starts at the root and walks down following the bits of the position number.

2Time

Insertion and removing the minimum are O(log n) in both versions. In the array, sift up or sift down takes at most the height of the tree. The linked structure adds nodeAt to find the last position; since that is O(log n) too, the total does not change, only the constant factor grows.

The difference shows up in building a heap. Building with an array is O(n), because every inner node is reached directly with items[i]. Building a linked heap calls nodeAt for every node and takes O(n log n).

3Memory and the cache

In the array an int takes 4 bytes. In the linked structure every node carries three pointers next to the value. On a 64-bit system that comes to 32 bytes per node with alignment, plus the record malloc keeps for each allocation. So the same heap takes eight times as much space or more when linked.

The array's elements sit next to each other in memory. When sift down goes from a node to its child, it often reads a cell that is already in the cache. Linked nodes can be scattered in memory, and every step jumps to a new address. Despite the same Big-O, the array version is clearly faster in practice.

The array's only drawback is capacity. The array in these lessons has a fixed size; real libraries allocate a bigger array and copy the elements when it fills up. Because this copying is rare, the average cost of insertion stays the same.

4Summary table

PropertyArrayLinked nodes
Look at the minimum (peek)O(1)O(1)
Insert, remove the minimumO(log n)O(log n), plus nodeAt
Build a heap from valuesO(n)O(n log n)
Reach node kO(1): items[k]O(log n): walking from the root
Parent and childrenIndex arithmeticThree pointers
Memory per element (int)4 bytesAbout 32 bytes, plus the malloc record
CapacityFixed or grownUntil memory runs out
Heap sortIn place, O(1) extra memoryNot suitable
Cache friendlinessGoodPoor: nodes are scattered

5What do libraries use?

Java's java.util.PriorityQueue and Python's heapq are both array-based binary min-heaps. Java grows its array when it fills up; Python arranges an ordinary list by the heap rule. C++'s std::priority_queue also works on an array (a vector), but its default is a max-heap.

import java.util.PriorityQueue; PriorityQueue<Integer> pq = new PriorityQueue<>();pq.add(40);pq.add(10);pq.add(25);System.out.println(pq.peek());   // 10System.out.println(pq.poll());   // 10System.out.println(pq.poll());   // 25
import heapq h = [40, 10, 25, 5]heapq.heapify(h)          # O(n): h is now a min-heapheapq.heappush(h, 15)print(heapq.heappop(h))   # 5print(h[0])               # 10: the minimum is always at h[0]

6Which one to choose?

  • Array: almost always. Priority queues, heap sort, the k largest elements and graph algorithms such as Dijkstra use an array-based heap.
  • Linked nodes: rarely chosen for a binary heap in real programs. You learn it to see that a heap is also a tree, how the same operations are done with pointers, and what the array gives you for free.

Pointers come into their own in other kinds of heap. Merging two binary heaps takes O(n) with an array. When two heaps have to be merged quickly, pointer-based structures such as the leftist heap, the binomial heap or the Fibonacci heap are used; they do not follow the binary heap's complete-tree rule.

If an exam asks "which is better", give the answer with reasons: insertion and removal are O(log n) in both, but the array wins at building with O(n), uses less memory per node and is cache friendly.

7Try it

Which operation is asymptotically slower on a linked heap than on an array heap?

Show the answer

The answer is A. Building with an array takes O(n), building a linked heap O(n log n), because nodeAt walks from the root to reach each node. Removal is O(log n) in both, and peeking is O(1) in both.

How does Python's heapq module store a heap?

Show the answer

The answer is A. heapq does not define a class of its own; it arranges the list you give it as an array-based min-heap. The list is not sorted, it only follows the heap rule, and the smallest value is at h[0].

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