Skip to content

Commit a2a1dee

Browse files
Merge pull request #1513 from Korra15/heapsort-algorithm
Added heap sort algorithm implemented in c++ #1500
2 parents 3965610 + 4c9c81b commit a2a1dee

1 file changed

Lines changed: 81 additions & 0 deletions

File tree

CPP/SortingTechniques/HeapSort.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <iostream>
2+
using namespace std;
3+
class heap1{
4+
public:
5+
void accept();
6+
void MAX_HEAPIFY(int a[],int,int);
7+
void BUILD_MAX_HEAP(int a[],int);
8+
void HEAPSORT(int a[],int);
9+
void display(int a[],int );
10+
};
11+
void heap1 :: MAX_HEAPIFY(int a[], int i, int n)
12+
{
13+
int l,r,largest,loc;
14+
l=2*i;
15+
r=(2*i+1);
16+
if((l<=n)&&a[l]>a[i])
17+
largest=l;
18+
else
19+
largest=i;
20+
if((r<=n)&&(a[r]>a[largest]))
21+
largest=r;
22+
if(largest!=i)
23+
{
24+
loc=a[i];
25+
a[i]=a[largest];
26+
a[largest]=loc;
27+
MAX_HEAPIFY(a, largest,n);
28+
}
29+
}
30+
void heap1 :: BUILD_MAX_HEAP(int a[], int n)
31+
{
32+
for(int k = n/2; k >= 1; k--)
33+
{
34+
MAX_HEAPIFY(a, k, n);
35+
}
36+
}
37+
void heap1 :: HEAPSORT(int a[], int n)
38+
{
39+
40+
BUILD_MAX_HEAP(a,n);
41+
int i, temp;
42+
for (i = n; i >= 2; i--)
43+
{
44+
temp = a[i];
45+
a[i] = a[1];
46+
a[1] = temp;
47+
MAX_HEAPIFY(a, 1, i - 1);
48+
}
49+
}
50+
51+
void heap1::accept(){
52+
int n;
53+
cout<<"Enter the number of students"<<endl;
54+
cin>>n;
55+
int a[n];
56+
cout<<"Enter the marks of the students "<<endl;
57+
for (int i = 1; i <= n; i++)
58+
{
59+
cin>>a[i];
60+
}
61+
HEAPSORT(a, n);
62+
display(a,n);
63+
}
64+
void heap1::display(int a[],int n){
65+
66+
cout<<":::::::SORTED MARKS::::::"<<endl;
67+
68+
for (int i = 1; i <= n; i++)
69+
{
70+
cout<<a[i]<<endl;
71+
}
72+
cout<<"Minimum marks obtained are:"<<a[1];
73+
cout<<"\nMaximum marks obtained are:"<<a[n];
74+
75+
}
76+
int main()
77+
{
78+
heap1 h;
79+
h.accept();
80+
return 0;
81+
}

0 commit comments

Comments
 (0)