We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 5
SNo:20 Esp. Name implementation of max heaps ate:2024-10-081
ln
Write a 6 program to implement may heap,
The following operations ace generally implemented on may heap.
fxd Deletes the maim element fom the heap.
ey int Rt
3. vole maxtteapfy (nt: Heapfies the subtree with the root at the ghen index so that the max-ordering property fs
2. vol nse rent to the heap
achieved.
4. vole print: Performs the breadth frst traversal of the heap andl prints the elements in the order
Source Code
[nome |
#include
using namespace std;
include "maxheap_operations..cpp"
int main() {
MaxHeap maxh(11);
int choice;
int element;
while(1) ¢
cout <<"1.Insert 2.Delete Maximum 3.Print 4.Exit\n
cout <<"Enter Your Choice: "
cin>>choice;
switch(choice) {
case 1:
cout<<"Enter an element
cin>>element;
maxh. insertKey(element );
break;
case 2:
maxh. deletetax();
break;
case 3
maxh.printQ):
break;
case 4:
exit(0);
,
return 0;
[tn acts |
#include
using namespace std;
void swap(int *x, int *y) ¢¥
class MaxHeap {
public
int heap_arr[20];
int capacity
int heap_siz
NaxHeap(int size){
this->capacity=size;
>
void insertKey(int);
void deleteMlax();
void MaxHeapify(int);
void print();
he
void MaxHeap: :insertKey(int k) {
this->heap_size++;
if(this->heap_size==20){
this->heap_size--;
pelset
this->heap_arr[this->heap_size]=
MaxHeapify(this->heap_size);
+
}
void MaxHeap: :deleteMax() {
if(this->heap_size<0){
cout<<"Heap is empty.*<heap_arr[0]<heap_arr[0]=this->heap_arr[this->heap_size];
this->heap_size--;
int i=0;
while(i*2+1<=this->heap_size+1){
int left_child=i*2;
int right_child=i#2+1;
int -max_inde:
if(this->heap_arr[1eft_child]>this->heap_arr(max_index] ){
max_index=left_child:
3
if(this->heap_arr[right_child]>this->heap_arr{max_index] ){
max_index=right_child;
}
if (max_index!=i){
swap(&this->heap_arr [i], this->heap_arr[max_index]);
ismax_index;
yelset
break:
}
,
+
void MaxHeap: :MaxHeapify(int i) {
if(i=*0) return;
int parent=(i#1)/2-1;
if(this->heap_arr[parent]heap_arr[iJ){
neering and Technology
SNA College of‘swap (&this->heap_arr [parent] ,athis->heap_arrlil):
MaxHeapi fy (parent);
,
+
void MaxHeap::print()
if(this->heap_size<0){
cout<<"Heap is empty. "<
elset
cout<<"Elements of the max heap are: ":
for(int i=0;i<-this->heap_size;i++){
cout<heap_arr[il<<" ";
+
cout<