#include <iostream>
#include <vector>
#include <algorithm>
// Function to insert into sorted array
void insertSorted(std::vector<int>& arr, int val) {
int i = arr.size() - 1;
arr.push_back(val); // add at end
// shift elements right to insert val in sorted order
while (i >= 0 && arr[i] > val) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = val;
}
// Function to remove min from sorted array
void removeMinSorted(std::vector<int>& arr) {
if (arr.empty()) return;
// shift elements left to remove first element
for (size_t i = 1; i < arr.size(); i++) {
arr[i - 1] = arr[i];
}
arr.pop_back();
}
// Heap helper functions
void heapInsert(std::vector<int>& heap, int val) {
heap.push_back(val);
int i = heap.size() - 1;
// bubble up
while (i > 0) {
int parent = (i - 1) / 2;
if (heap[parent] <= heap[i]) break;
std::swap(heap[parent], heap[i]);
i = parent;
}
}
void heapRemoveMin(std::vector<int>& heap) {
if (heap.empty()) return;
heap[0] = heap.back();
heap.pop_back();
int i = 0;
int n = heap.size();
// bubble down
while (true) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;
if (left < n && heap[left] < heap[smallest]) smallest = left;
if (right < n && heap[right] < heap[smallest]) smallest = right;
if (smallest == i) break;
std::swap(heap[i], heap[smallest]);
i = smallest;
}
}
void printArray(const std::vector<int>& arr) {
for (size_t i = 0; i < arr.size(); i++) {
std::cout << arr[i];
if (i != arr.size() - 1) std::cout << " -> ";
}
std::cout << "\n";
}
void printHeap(const std::vector<int>& heap) {
// Print heap as array
for (size_t i = 0; i < heap.size(); i++) {
std::cout << heap[i];
if (i != heap.size() - 1) std::cout << " -> ";
}
std::cout << "\n";
}
int main() {
std::vector<int> sortedArr = {1, 3, 5, 7, 9};
std::vector<int> heap = {1, 3, 5, 7, 9};
// Make heap a valid min-heap
std::make_heap(heap.begin(), heap.end(), std::greater<>());
// Insert 4
insertSorted(sortedArr, 4);
heapInsert(heap, 4);
// Remove min
removeMinSorted(sortedArr);
heapRemoveMin(heap);
std::cout << "Sorted Array after insert and remove min:\n";
printArray(sortedArr);
std::cout << "Heap after insert and remove min (array form):\n";
printHeap(heap);
return 0;
}while (i >= 0 && arr[i] > val) { arr[i + 1] = arr[i]; i--; }
Shift elements right to insert new value in sorted order
for (size_t i = 1; i < arr.size(); i++) { arr[i - 1] = arr[i]; }
Shift elements left to remove smallest element
while (i > 0) { int parent = (i - 1) / 2; if (heap[parent] <= heap[i]) break; swap; i = parent; }
Bubble up inserted element to maintain heap order
while (true) { find smallest child; if (smallest == i) break; swap; i = smallest; }
Bubble down root element after removal to maintain heap order
Sorted Array after insert and remove min:
3 -> 4 -> 5 -> 7 -> 9
Heap after insert and remove min (array form):
3 -> 4 -> 5 -> 7 -> 9