Consider a priority queue implemented using a sorted array and a heap. Which statement best explains why heaps are preferred for insertions?
Think about how much shifting or reordering is needed when inserting into a sorted array versus a heap.
Inserting into a sorted array requires shifting elements to keep the array sorted, which takes O(n) time. A heap maintains a partial order and allows insertion by adding the element at the end and then 'bubbling up' in O(log n) time.
Given the sequence of insertions: 5, 3, 8 into an empty min-heap and an empty sorted array, what is the final state of each data structure?
/* Min-heap insertion order: 5, 3, 8 */ /* Sorted array insertion order: 5, 3, 8 */
Remember that a min-heap always keeps the smallest element at the root, and a sorted array keeps elements in ascending order.
After inserting 5, 3, 8 into a min-heap, the smallest element 3 becomes the root, followed by 5 and 8. The sorted array keeps elements sorted as 3, 5, 8.
What is the time complexity of extracting the minimum element from a min-heap compared to a sorted array?
Consider how the data structure is organized and what operations are needed to remove the minimum element.
Extracting the minimum from a min-heap takes O(log n) time because the heap needs to reorder after removal. In a sorted array, the minimum is at the start, so removal is O(n) due to shifting elements.
Which reason best explains why sorted arrays are inefficient for supporting both insertion and extraction operations in priority queues?
Think about what happens to the elements after you insert or remove one in a sorted array.
Inserting into a sorted array requires shifting elements to keep order, which is O(n). Extracting the minimum (usually the first element) also requires shifting all other elements, which is O(n). This makes both operations inefficient.
Choose the best explanation for why heaps are used instead of sorted arrays when both insertion and extraction operations are frequent.
Consider the time complexities of insertion and extraction in both data structures.
Heaps maintain a partial order allowing both insertion and extraction in O(log n) time, which is efficient for frequent operations. Sorted arrays require O(n) time for either insertion or extraction due to shifting elements.
