forked from smilegupta/Mastering_DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap Sort.cpp
More file actions
72 lines (67 loc) · 1.04 KB
/
Heap Sort.cpp
File metadata and controls
72 lines (67 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include< iostream>
#include< conio.h>
using namespace std;
int a[50],i,n;
void display();
void makeheap(int);
void heapsort();
int main()
{
cout<<"Enter the number of elements to enter : ";
cin>>n;
cout<<"enter element:";
for(i=0;i< n;i++)
{
//cout<< i+1<<": ";
cin>>a[i];
}
makeheap(n);
for(i=0;i< n;i++)
{
cout<< a[i]<<" ";
}
heapsort();
cout<<"****HEAPSORT****"<< endl;
display();
getch();
}
void makeheap(int n)
{
int val,k,par;
for(i=1;i< n;i++)
{
val=a[i];
k=i;
par=(k-1)/2;
while(k>0&&a[par]< val)
{
a[k]=a[par];
k=par;
par=(k-1)/2;
a[k]=val;
}
}
// for(i=0;i< n;i++)
// {
// cout<< a[i]<<" ";
//}
cout<< endl;
}
void heapsort()
{
int temp;
for(i=n-1;i>0;i--)
{
temp=a[i];
a[i]=a[0];
a[0]=temp;
makeheap(i);
}
}
void display()
{
for(i=0;i< n;i++)
{
cout<< a[i]<<" ";
}
}