[   ^ to index...   |   <-- previous   |   next -->   ]

Heapsort

IDEA: "Turn the array into a heap. Then, pop_max off the heap, re-heapify, and repeat."

Heapsort is my personal favorite O(nlogn) sort. Unlike quicksort, it has deterministic O(nlogn) time, and unlike mergesort it does not require O(n) extra space.

In order to understand heapsort, however, you need to understand the "heap" data structure. (Note: The "heap" data structure has no relationship with the notion of "heap", a.k.a. "free store" or "dynamically allocated", memory.)

In order to understand heaps, in turn, you must understand binary trees. A binary tree is a data structure that, like linked lists, consists of nodes and links. However, a binary tree has up to two links per node:

[diagram of a binary tree]

You will see other definitions of the heap data structure, but Corman, Leiserson, and Rivest define a heap as an array viewed as a nearly-complete, balanced binary tree that satisfies the heap property:

25 21 18 13 15 18 10 8 2 10 7 11

For any index k (starting at 1), the children are the elements at index 2k and 2k+1:

[diagram of a heap]

The heap property is as follows: every node's value is greater than or equal to the value of its children.


Last modified: Tue Aug 8 10:26:17 PDT 2000