You are on page 1of 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