forked from tarunguptaraja/Algorithms-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheap_sort.cpp
More file actions
52 lines (48 loc) · 1.59 KB
/
heap_sort.cpp
File metadata and controls
52 lines (48 loc) · 1.59 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
#include<iostream>
using namespace std;
void maxHeapify(int heap[],int i,int n)
{
int left=2*i;
int right=2*i+1;
int largest=i;
if(left <=n && heap[i]<heap[left])
largest = left;
if(right <=n && heap[largest]<heap[right])
largest = right; right;
if(largest !=i)
{
int temp=heap[largest];
heap[largest]=heap[i];
heap[i]=temp;
maxHeapify(heap,largest,n);
}
}
void buildHeap(int heap[],int n)
{
for (int i=n/2;i>=1;i--)
maxHeapify(heap,i,n);
}
int main()
{
int n;
cout<<"Number of elements";
cin>>n;
int heap[n+1];
cout<<"Enter elements"<<endl;
for(int i=1;i<=n;i++)
cin>>heap[i];
buildHeap(heap,n);
int heapsize=n;
for(int i=n;i>=2;i--)
{
int temp=heap[1];
heap[1]=heap[i];
heap[i]=temp;
--heapsize;
maxHeapify(heap,1,heapsize);
}
cout<<" After sorting "<<endl;
for(int i =1;i<=n;i++)
cout<<heap[i]<<" ";
return 0;
}