0% found this document useful (0 votes)
21 views2 pages

#Includebitsstdc++ H

The document defines a heap class with methods to push elements onto the heap, pop the maximum element, get the top element, and check if the heap is empty. It also defines heapify functions to maintain the heap property during insertion and deletion. Finally, it implements heapsort using these heap functions to sort an integer array in ascending order.

Uploaded by

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

#Includebitsstdc++ H

The document defines a heap class with methods to push elements onto the heap, pop the maximum element, get the top element, and check if the heap is empty. It also defines heapify functions to maintain the heap property during insertion and deletion. Finally, it implements heapsort using these heap functions to sort an integer array in ascending order.

Uploaded by

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

#include<bits/stdc++.

h>
using namespace std;

class heap{
int arr[100];
public:
int size=0;
void push(int val){
size=size+1;
int index=size;
arr[index]=val;
while(index>1){
int parent =index/2;
if(arr[index]>arr[parent]){
swap(arr[index],arr[parent]);
index=parent;
}
else{
return;
}
}
}
void heapify(int i){
int largest=i;
int left=2*i;
int right=2*i+1;
if(left<=size && arr[left]>arr[largest]){
largest=left;
}
if(right<=size && arr[right]>arr[largest]){
largest=right;
}
if(largest!=i){
swap(arr[i],arr[largest]);
heapify(largest);
}
}
void pop(){
arr[1]=arr[size];
size--;
heapify(1);
}
int top(){
return arr[1];
}
bool is_empty(){
return size;
}
};
//////////////////////////////////////////////////////
void heapify1(int arr[],int i,int size){
int largest=i;
int left=2*i;
int right=2*i+1;
if(left<=size && arr[left]>arr[largest]){
largest=left;
}
if(right<=size && arr[right]>arr[largest]){
largest=right;
}
if(largest!=i){
swap(arr[i],arr[largest]);
heapify1(arr,largest,size);
}
}

void Hsort(int arr[],int n){


for(int i=n/2;i>0;i--){
heapify1(arr,i,n);
}
int size=n;
while(size>1){
swap(arr[size],arr[1]);
size--;
heapify1(arr,1,size);
}
for(int i=1;i<=n;i++){
cout<<arr[i]<<" ";
}
}

//////////////////////////////////////////////////////

int main(){
// heap h;
// h.push(9);
// h.push(4);
// h.push(21);
// h.push(15);
// cout<<h.top();
// h.pop();
// cout<<h.top();
// h.pop();
// cout<<h.top();
// cout<<h.is_empty();
int arr[]={0,3,1,4,5,2};
Hsort(arr,5);
}

You might also like