Imagine you have a list of numbers that you want to keep sorted. You can use a sorted array or a heap. Why is a heap better if you need to add new numbers often?
Think about how much work it takes to keep the list sorted after adding a new number.
Inserting into a sorted array requires shifting elements to keep order, which takes more time. A heap allows insertion in logarithmic time without full reordering.
What is the state of the min-heap after inserting the numbers 5, 3, 8, 1 in this order?
std::vector<int> heap; // Insert 5 heap.push_back(5); std::push_heap(heap.begin(), heap.end(), std::greater<>()); // Insert 3 heap.push_back(3); std::push_heap(heap.begin(), heap.end(), std::greater<>()); // Insert 8 heap.push_back(8); std::push_heap(heap.begin(), heap.end(), std::greater<>()); // Insert 1 heap.push_back(1); std::push_heap(heap.begin(), heap.end(), std::greater<>()); // Print heap elements in order stored in vector
Remember that a min-heap keeps the smallest element at the front, but the rest is not fully sorted.
After each insertion, the heap property is maintained. The smallest element (1) is at the front, and the rest follow heap order, not sorted order.
Given a min-heap and a sorted array containing the same elements, which data structure allows faster search for an arbitrary element and why?
std::vector<int> sorted_array = {1, 3, 5, 8}; std::vector<int> heap = {1, 3, 8, 5}; // min-heap representation // Searching for element 5 in both structures
Think about how elements are arranged and how you find a number in each structure.
A sorted array allows binary search, which is fast. A heap only guarantees the smallest element at the top, so searching for any other element requires checking many elements.
Explain why a sorted array is not efficient when you need to both insert new elements quickly and extract the minimum element quickly.
Think about what happens inside the array when you add or remove elements.
Inserting into a sorted array requires shifting elements to keep order, which is slow. Extracting the minimum requires removing the first element and shifting the rest, which is also slow, making both operations inefficient.
Which property of heaps makes them suitable for priority queues, supporting fast insertion and fast extraction of the minimum or maximum element?
Think about how heaps organize elements compared to fully sorted arrays.
Heaps maintain a partial order where the root is the smallest (min-heap) or largest (max-heap), allowing fast access and efficient insertion without full sorting.