Intermediate Topic 22 of 52 Data Structures
Heaps
Complete trees satisfying a parent-versus-child ordering property.
How it works
A heap is a complete binary tree in which each parent is ordered with respect to its children: in a max-heap it is at least as large as both, in a min-heap at most. The root is therefore always the extreme element. Because it is complete, it is stored compactly in an array, with children of index i at 2i+1 and 2i+2, and the root is readable in O(1).
Where it is used
Priority queues, heapsort, finding the k smallest or largest elements, merging sorted streams, Dijkstra's algorithm and memory allocators use heaps. Heaps are not related to the program heap memory.
Common pitfall
A heap is only partially ordered, so it cannot search for arbitrary keys quickly or iterate in sorted order. Off-by-one errors in index arithmetic are common between zero-based and one-based layouts. Building from n items with the bottom-up method is O(n), faster than n separate inserts.
Where it fits in the course
Heaps is topic 22 of 52 in Data Structures, rated Intermediate. It follows B+ Trees. The next topic is Binary Heap Operations.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Data Structures quiz.
- Explore the Binary Search Tree visualizer: Insert keys and run traversals.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Data Structures quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Heaps?
Where do people use Heaps?
What is the most common mistake with Heaps?
What should I learn before this topic?
How can I practice it?
Is Heaps hard to learn?
How long does it take to learn Heaps?
Which topics are related to Heaps?
What should I study after Heaps?
Related topics
- B+ Trees (Data Structures)
- Binary Heap Operations (Data Structures)
- B-Trees (Data Structures)
- Tries (Data Structures)