-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.cpp
More file actions
47 lines (46 loc) · 955 Bytes
/
HeapSort.cpp
File metadata and controls
47 lines (46 loc) · 955 Bytes
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
#include<bits/stdc++.h>
using namespace std;
maxHeapify(int A[],int i, int heapSize)
{
int largest=i;
int l=2*i+1;
int r=2*i+2;
if(l<heapSize && A[l]>A[largest])
largest=l;
if(r<heapSize && A[r]>A[largest])
largest=r;
if(largest!=i)
{
swap(A[largest],A[i]);
maxHeapify(A,largest,heapSize);
}
}
BuildMaxHeap(int A[],int heapSize)
{
for(int i=(heapSize/2)-1;i>=0;i--)
maxHeapify(A,i,heapSize);
}
HeapSort(int A[],int heapSize)
{
BuildMaxHeap(A,heapSize);
for(int i=heapSize-1;i>=0;i--)
{
swap(A[0],A[i]);
heapSize--;
maxHeapify(A,0,heapSize);
}
}
int main()
{
int n;
cout<<"Enter the no of nodes : "<<endl;
cin>>n;
int A[n];
int heapSize=sizeof(A)/sizeof(A[0]);
cout<<"Enter the nodes"<<endl;
for(int i=0;i<n;i++)
cin>>A[i];
HeapSort(A, heapSize);
for(int i=0;i<n;i++)
cout<<A[i]<<" ";
}