Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

CSL-221 Data structure &

Algorithm

Semester 03-A
SALAL AHMED
02-134211-107

Lab 11: Implementation of Heap and Priority Queue

#include <iostream>
using namespace std;
void max_heap(int *a, int m, int n) {
int j, t;
t = a[m];
j = 2 * m;
while (j <= n) {
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (t > a[j])
break;
else if (t <= a[j]) {
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = t;
return;}
void build_maxheap(int *a, int n) {
int k;
for (k = n / 2; k >= 1; k--) {
max_heap(a, k, n);
}}
void Get_Max(int *a){
cout << "LARGEST ELEMENT ON HEAP: " << a[1];}
int main() {
int i;
int n = 9;
cout << "ENTER TOTAL NO. OF ARRAY ELEMENTS YOU WANT TO SHOW: ";
cin >> n;
cout << "----------------------------------------------------" << endl;
int a[20];
for (i = 1; i <= n; i++){
cout << "Enter element no. " << (i) << ": ";
cin >> a[i];
cout << endl;}
build_maxheap(a, n);
cout << "Max Heap:\n";
for (i = 1; i <= n; i++) {
cout << a[i] << endl;}
Get_Max(a);
cout << "\n\n";
system("pause");}
CSL-221 Data structure &
Algorithm

Semester 03-A
SALAL AHMED
02-134211-107

You might also like