forked from atiqisrak/AdvancedAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapDescending.cpp
More file actions
55 lines (48 loc) · 1.02 KB
/
Copy pathHeapDescending.cpp
File metadata and controls
55 lines (48 loc) · 1.02 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
#include <iostream>
using namespace std;
void heapify(int* heap, int i, int n)
{
int left = 2*i;
int right = 2*i+1;
int smallest = i;
if( left <= n && heap[left]<heap[i])
smallest = left;
if( right <= n && heap[right]<heap[smallest])
smallest = right;
if(smallest != i)
{
int temp = heap[smallest];
heap[smallest] = heap[i];
heap[i] = temp;
heapify(heap,smallest,n);
}
}
void buildHeap(int* heap,int n)
{
for(int i=n/2;i>=1;i--)
heapify(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--;
heapify(heap,1,heapSize);
}
//cout<<" After Sorting\n";
for(int i=1;i<=n;i++)
cout<<" "<<heap[i];
return 0;
}