CODE IN CPP FOR HEAPIFY INSERT OPERATION IN BINARY
Tue Feb 04 2025 06:34:13 GMT+0000 (Coordinated Universal Time)
Saved by
@Mitali
#include <iostream>
#include <vector>
using namespace std;
class BinaryHeap {
private:
vector<int> heap;
void heapifyUp(int index) {
int parent = (index - 1) / 2;
if (index > 0 && heap[index] > heap[parent]) {
swap(heap[index], heap[parent]);
heapifyUp(parent);
}
}
public:
BinaryHeap() {
heap.push_back(-1);
}
void insert(int value) {
heap.push_back(value);
heapifyUp(heap.size() - 1);
}
void printHeap() {
for (int i = 1; i < heap.size(); i++) {
cout << heap[i] << " ";
}
cout << endl;
}
};
int main() {
BinaryHeap heap;
heap.insert(10);
heap.insert(20);
heap.insert(5);
heap.insert(30);
heap.insert(15);
cout << "Heap after insertions: ";
heap.printHeap();
return 0;
}
content_copyCOPY
Comments