Answer to Guiding Questions
Before implementing the d-ary MinHeap class, let's address the guiding questions to ensure a proper understanding of the underlying data structure and its operations.
1. Parent Index Calculation
Question:
If you put a complete d-ary tree in an array (0-indexed), what is the index of the parent of the node at position i?
Answer:
In a d-ary heap stored in a 0-indexed array, the parent of the node at index i can be calculated using the formula:
[
\text{parent}(i) = \left\lfloor \frac{(i - 1)}{d} \right\rfloor
]
Explanation:
- d-ary Heap: Each node has up to
d children.
- 0-Indexed Array: The first element is at index
0.
- Parent Calculation: For any node at index
i, subtracting 1 and dividing by d gives the parent index. The floor operation ensures we get an integer value.
Example:
For a ternary heap (d = 3):
- Node at index
4:
Parent index = floor((4 - 1)/3) = floor(1) = 1
- Node at index
7:
Parent index = floor((7 - 1)/3) = floor(2) = 2
2. Children Indices Calculation
Question:
In the same scenario as above, what are the indices of the children of the node at position i?
Answer:
For a node at index i in a 0-indexed d-ary heap, the indices of its children are:
[
\text{child}(j) = d \times i + j \quad \text{for} \quad j = 1 \text{ to } d
]
So, the children indices are:
[
d \times i + 1, \quad d \times i + 2, \quad \ldots, \quad d \times i + d
]
Explanation:
- Child Calculation: Starting from 1 to
d, each child index is offset by d times the parent index plus the child number.
Example:
For a ternary heap (d = 3) and node at index 2:
- Children indices:
3 * 2 + 1 = 7
3 * 2 + 2 = 8
3 * 2 + 3 = 9
3. Changes in Heap Functions for d-ary Arrays
Question:
What changes in the heap functions you learned in class when you move to d-ary arrays?
Answer:
When transitioning from a binary heap to a d-ary heap, several modifications are necessary in the heap operations:
-
Parent and Child Calculations:
- Parent: Use the formula (\left\lfloor \frac{(i - 1)}{d} \right\rfloor) to find the parent.
- Children: Calculate children using (d \times i + 1) to (d \times i + d).
-
Percolate Up:
- Similar to binary heap but only involves comparing with the single parent.
-
Percolate Down:
- Instead of comparing with two children, compare the node with all
d children to find the smallest.
- Swap with the smallest child if necessary and continue percolating down.
-
Add Operation:
- Insert the new element at the end of the array.
- Percolate up to maintain the heap property.
-
Remove Operation:
- Replace the root with the last element.
- Percolate down to maintain the heap property, considering all
d children.
-
Efficiency:
- Time Complexity: Operations like insert and remove have time complexity (O(\log_d n)), which is generally better for larger
d as the height of the heap decreases.
Implementation of d-ary MinHeap Class
Below is the implementation of the d-ary MinHeap class in MinHeap.h based on the provided interface and the guiding principles discussed above.
// MinHeap.h
#ifndef MINHEAP_H
#define MINHEAP_H
#include <vector>
#include <stdexcept>
// Define a structure to hold the heap elements and their priorities
template <class T>
struct HeapNode {
T item;
int priority;
HeapNode(const T& itm, int prio) : item(itm), priority(prio) {}
};
template <class T>
class MinHeap {
public:
// Constructor that builds a d-ary Min Heap
// This should work for any d >= 2,
// but doesn't have to do anything for smaller d.
MinHeap(int d);
// Destructor
~MinHeap();
// Adds the item to the heap with the given priority
void add(T item, int priority);
// Returns the element with smallest priority
// Throws an exception if the heap is empty
const T& peek() const;
// Removes the element with smallest priority
// Throws an exception if the heap is empty
void remove();
// Returns true if and only if there are no elements on the heap
bool isEmpty() const;
private:
std::vector<HeapNode<T>> heap; // Internal storage for heap elements
int d; // The 'd' in d-ary heap
// Helper function to percolate up the element at index i
void percolateUp(int i);
// Helper function to percolate down the element at index i
void percolateDown(int i);
// Helper function to find the index of the child with minimum priority
// Returns -1 if the node has no children
int minChild(int i) const;
};
// Implementation
// Constructor
template <class T>
MinHeap<T>::MinHeap(int d_) : d(d_) {
if (d < 2) {
throw std::invalid_argument("Degree 'd' must be at least 2.");
}
}
// Destructor
template <class T>
MinHeap<T>::~MinHeap() {
// No dynamic memory to free since we're using std::vector
}
// Add method
template <class T>
void MinHeap<T>::add(T item, int priority) {
heap.emplace_back(item, priority);
percolateUp(static_cast<int>(heap.size()) - 1);
}
// Peek method
template <class T>
const T& MinHeap<T>::peek() const {
if (heap.empty()) {
throw std::out_of_range("Heap is empty.");
}
return heap[0].item;
}
// Remove method
template <class T>
void MinHeap<T>::remove() {
if (heap.empty()) {
throw std::out_of_range("Heap is empty.");
}
// Replace root with the last element
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty()) {
percolateDown(0);
}
}
// isEmpty method
template <class T>
bool MinHeap<T>::isEmpty() const {
return heap.empty();
}
// Percolate Up helper
template <class T>
void MinHeap<T>::percolateUp(int i) {
if (i == 0) return; // Already at root
int parent = (i - 1) / d;
// If current node has a lower priority than parent, swap
if (heap[i].priority < heap[parent].priority) {
std::swap(heap[i], heap[parent]);
percolateUp(parent);
}
}
// Percolate Down helper
template <class T>
void MinHeap<T>::percolateDown(int i) {
int smallest = i;
int child = minChild(i);
// Compare with the smallest child
if (child != -1 && heap[child].priority < heap[smallest].priority) {
smallest = child;
}
if (smallest != i) {
std::swap(heap[i], heap[smallest]);
percolateDown(smallest);
}
}
// minChild helper to find the child with the minimum priority
template <class T>
int MinHeap<T>::minChild(int i) const {
int start = d * i + 1;
int end = d * i + d;
if (start >= static_cast<int>(heap.size())) {
return -1; // No children
}
// Initialize with the first child
int minIndex = start;
int minPriority = heap[start].priority;
// Iterate through all possible children to find the one with minimum priority
for (int j = start + 1; j <= end && j < static_cast<int>(heap.size()); ++j) {
if (heap[j].priority < minPriority) {
minPriority = heap[j].priority;
minIndex = j;
}
}
return minIndex;
}
#endif // MINHEAP_H
Explanation of the Implementation
-
HeapNode Structure:
- A
HeapNode structure is defined to store each element (item) along with its associated priority.
-
MinHeap Class Members:
std::vector<HeapNode<T>> heap;
- Used to store the heap elements in a compact array format.
int d;
- Represents the degree of the heap (i.e., the number of children each node can have).
-
Constructor:
- Initializes the heap with the specified degree
d.
- Throws an exception if
d is less than 2, as a heap must have at least two children per node.
-
Destructor:
- No explicit action is needed since
std::vector manages its own memory.
-
add Method:
- Adds a new
HeapNode to the end of the heap vector.
- Calls
percolateUp to maintain the heap property by moving the new node to its correct position.
-
peek Method:
- Returns the
item of the root node (which has the smallest priority).
- Throws an exception if the heap is empty.
-
remove Method:
- Removes the root node (element with the smallest priority).
- Replaces the root with the last element in the heap.
- Calls
percolateDown to maintain the heap property.
- Throws an exception if the heap is empty.
-
isEmpty Method:
- Checks if the heap is empty by verifying if the
heap vector has no elements.
-
percolateUp Helper Method:
- Moves an element at index
i up the heap until the heap property is restored.
- Compares the current node with its parent and swaps if necessary.
-
Helper Method:
Usage Example
Here's a simple example demonstrating how to use the MinHeap class:
#include <iostream>
#include "MinHeap.h"
int main() {
// Create a ternary (3-ary) min heap
MinHeap<std::string> heap(3);
// Add elements to the heap
heap.add("apple", 5);
heap.add("banana", 3);
heap.add("cherry", 4);
heap.add("date", 1);
heap.add("elderberry", 2);
// Peek at the smallest element
std::cout << "Top element: " << heap.peek() << std::endl; // Should print "date"
// Remove elements in order
while (!heap.isEmpty()) {
std::cout << "Removing: " << heap.peek() << std::endl;
heap.remove();
}
return 0;
}
Expected Output:
Top element: date
Removing: date
Removing: elderberry
Removing: banana
Removing: cherry
Removing: apple
Notes
-
Exception Handling: The class throws std::invalid_argument if initialized with d < 2 and std::out_of_range when attempting to peek or remove from an empty heap. Ensure to handle these exceptions appropriately in your application.
-
Template Class: The MinHeap class is a template class, allowing it to handle any data type T. Ensure that the type T supports copying and assignment.
-
Efficiency Considerations:
- Time Complexity: The
add and remove operations have a time complexity of (O(\log_d n)), where n is the number of elements in the heap.
- Space Complexity: The heap uses (O(n)) space to store
n elements.
This implementation provides a flexible and efficient d-ary min heap that can be easily integrated into various applications requiring priority queue functionalities.