Skip to content

Create Heap Sort.cpp #230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions CPP/Heap Sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <iostream>
using namespace std;
#define MAX 100
void maxheapify(int *a,int,int);
void heapsort(int *a,int);
void printarray(int *a,int);
int main(){
int n,i,a[MAX];
cout<<"Enter the number of elements you want: ";
cin>>n;
cout<<"The entered elements are: ";
for(i=0;i<n;i++){
cin>>a[i];
}
heapsort(a,n);
printarray(a,n);
}
void heapsort(int *a,int n){
for(int i=n/2-1;i>=0;i--){
maxheapify(a,n,i);
}

for(int i=n-1;i>=0;i--){
int c=a[0];
a[0]=a[i];
a[i]=c;
maxheapify(a,i-1,0);
}
}

void maxheapify(int *a,int n,int i){
int largest=i;
int left=(2*i)+1;
int right=(2*i)+2;
if(left<=n && a[left]>a[largest]){
largest=left;
}
if(right<=n && a[right]>a[largest]){
largest=right;
}
if(largest!=i){
int c=a[i];
a[i]=a[largest];
a[largest]=c;
maxheapify(a,n,largest);
}
}
void printarray(int *a,int n){
cout<<"The elements in sorted array are: ";
for(int i=0;i<n;i++){
cout<<a[i]<<' ';
}
}