forked from anupam-kumar-krishnan/Competitive_Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_sort.cpp
54 lines (53 loc) · 1.1 KB
/
Heap_sort.cpp
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
#include <bits/stdc++.h>
#include <algorithm>
#include <set>
#include <math.h>
#include <vector>
#define int long long
#define mode 998244353
using namespace std;
class Solution
{
public:
void heapify(int a[], int n, int x) {
int l=x;
int left = (2*x)+1;
int right = (2*x)+2;
if(left<n && a[left]>a[l]){
l=left;
}
if(right<n && a[right]>a[l]){
l=right;
}
if(l!=x){
swap(a[x] , a[l]);
heapify(a , n , l);
}
}
public:
void buildHeap(int arr[], int n) {
int x;
x = (n/2)-1;
for(int i=x;i>=0;i--){
heapify(arr , n , i);
}
}
public:
void heapSort(int a[], int n){
buildHeap(a , n);
for(int i=n-1;i>=0;i--){
swap(a[0] , a[i]);
heapify(a, i ,0);
}
}
};
int32_t main(){
int n = 5;
int arr[] = {4,1,3,9,7};
Solution ob;
ob.heapSort(arr , n);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}