What is the advantage of Heaps over Sorted Arrays?

Technology CommunityCategory: ArraysWhat is the advantage of Heaps over Sorted Arrays?
VietMX Staff asked 3 years ago
Problem

What is the advantage of dealing with the complexity of inserting into a heap given an algorithm like quick sort handles sorting very well?

find-min (resp. find-max), delete-min (resp. delete-max) and insert are the three most important operations of a min-heap (resp. max-heap), and they usually have complexity of O(1)O(log n) and O(log n) respectively if you implement a min/max-heap by a binary tree.

Now suppose instead you implement a min-heap by a sorted (non-decreasing) array (The case for max-heap is similar). find-min and delete-min are of O(1) complexity if insert is not required in your application, since you can maintain a pointer p that always points to the minimum element in your array. When the minimum element is removed, you just need to move p one step to the next element in the array.

Dealing with insertion in a sorted array is not trivial. Given a new element e, we can use binary search to locate its position in the array to insert it. But the point is that if you want to insert it there, you have to move a lot of old elements (can be O(n)) around to make a vacancy for the new element to reside. This is quite inefficient for most applications. You may also choose to re-sort the array after an element is inserted, this requires O(n log n) time however.

Where a heap absolutely, completely beats sorting arrays is a situation where small numbers of items are removed or added, and after each change you want to know again which is the smallest element.