Why Heap Exists and What Sorted Array Cannot Do Efficiently in DSA C++ - Performance Analysis
We want to understand why heaps are useful compared to sorted arrays.
Specifically, what tasks are slow with sorted arrays but faster with heaps?
Analyze the time complexity of these operations on a sorted array:
// Insert element into sorted array
void insertSorted(int arr[], int &n, int x) {
int i = n - 1;
while (i >= 0 && arr[i] > x) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = x;
n++;
}
// Remove smallest element (first element)
void removeMin(int arr[], int &n) {
for (int i = 1; i < n; i++) {
arr[i - 1] = arr[i];
}
n--;
}
This code inserts an element keeping the array sorted and removes the smallest element.
Look at the loops that repeat work:
- Primary operation: Shifting elements to insert or remove.
- How many times: Up to n times for each insert or remove.
As the array size grows, the number of shifts grows too.
| Input Size (n) | Approx. Operations (shifts) |
|---|---|
| 10 | Up to 10 shifts |
| 100 | Up to 100 shifts |
| 1000 | Up to 1000 shifts |
Pattern observation: The work grows linearly with input size.
Time Complexity: O(n)
This means inserting or removing elements in a sorted array takes time proportional to the number of elements.
[X] Wrong: "Since the array is sorted, insertion and removal must be very fast like O(1)."
[OK] Correct: Even though the array is sorted, inserting or removing requires shifting many elements, which takes time proportional to the array size.
Understanding why heaps exist helps you explain trade-offs in data structures clearly.
This skill shows you can choose the right tool for efficient operations in real problems.
"What if we used a heap instead of a sorted array? How would the time complexity for insertion and removal change?"