0% found this document useful (0 votes)
16 views3 pages

Dsa assignment

Uploaded by

arsalan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Dsa assignment

Uploaded by

arsalan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1.

Max-Heap: Insert and Display After Every Insertion :

#include <iostream>
#include <vector>
using namespace std;

void heapifyUpMax(vector<int> &heap, int index) {


int parent = (index - 1) / 2;
while (index > 0 && heap[index] > heap[parent]) {
swap(heap[index], heap[parent]);
index = parent;
parent = (index - 1) / 2;
}
}

void insertMaxHeap(vector<int> &heap, int value) {


heap.push_back(value);
heapifyUpMax(heap, heap.size() - 1);
}

void displayHeap(const vector<int> &heap) {


for (int val : heap) {
cout << val << " ";
}
cout << endl;
}

int main()
{
vector<int> input = {50, 30, 40, 10, 20, 60};
vector<int> maxHeap;

cout << "Max-Heap after each insertion:" << endl;


for (int value : input) {
insertMaxHeap(maxHeap, value);
displayHeap(maxHeap);
}
return 0;
}
OUTPUT :

2. Min-Heap: Insert and Display After Every Insertion :

#include <iostream>
#include <vector>
using namespace std;

void heapifyUpMin(vector<int> &heap, int index) {


int parent = (index - 1) / 2;
while (index > 0 && heap[index] < heap[parent]) {
swap(heap[index], heap[parent]);
index = parent;
parent = (index - 1) / 2;
}
}

void insertMinHeap(vector<int> &heap, int value) {


heap.push_back(value);
heapifyUpMin(heap, heap.size() - 1);
}

void displayHeap(const vector<int> &heap) {


for (int val : heap) {
cout << val << " ";
}
cout << endl;
}

int main() {
vector<int> input = {50, 30, 40, 10, 20, 60};
vector<int> minHeap;

cout << "Min-Heap after each insertion:" << endl;


for (int value : input) {
insertMinHeap(minHeap, value);
displayHeap(minHeap);
}
return 0;
}
OUTPUT:

You might also like