1. Brute Force — Sift-Up Sequential Insertion
Intuition
Simulate inserting elements into a binary heap one by one. For each index i from 1 to N-1, compare with parent at (i-1)/2 and swap upwards while element is greater than parent.
When to apply: When elements arrive one at a time via a streaming source.
Algorithm
- Step 1: Loop i from 1 to N - 1.
- Step 2: While i > 0 and arr[i] > arr[(i - 1) / 2], swap arr[i] with arr[(i - 1) / 2].
- Step 3: Update i = (i - 1) / 2.
- Step 4: Continue until all elements have sifted up.
#include <iostream>#include <vector>using namespace std; class Solution {public: void buildHeap(vector<int>& arr) { int n = arr.size(); for (int i = 1; i < n; i++) { int curr = i; while (curr > 0) { int parent = (curr - 1) / 2; if (arr[curr] > arr[parent]) { swap(arr[curr], arr[parent]); curr = parent; } else { break; } } } }}; int main() { Solution sol; vector<int> arr = {4, 10, 3, 5, 1}; sol.buildHeap(arr); cout << "Max-Heap (Sift-Up): "; for (int x : arr) cout << x << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— O(N log N) because elements near leaves must traverse up the entire tree. - Space complexity:
O(1)— O(1) auxiliary space as swaps are in-place.
Why Brute Force Doesn't Scale:
With N = 107, O(N log N) requires ~2.4 * 108 operations, whereas Floyd's algorithm requires ~2 * 107 operations.
Building a heap of 10 million elements takes ~45ms with Floyd's method versus ~600ms with successive sift-up.