-
Notifications
You must be signed in to change notification settings - Fork 98
/
heapSort.cpp
96 lines (73 loc) · 1.21 KB
/
heapSort.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Heapsort and Min heap in C++
#include<iostream>
#include<vector>
using namespace std;
#define ll long long
void heapify(int i, vector<ll> &v)
{
if(v.empty() || 2*i+1>=v.size() || i<0)
return;
// int k=v[2*i+1]<v[(2*i)+2]?(2*i+1):(2*i+2);
int k= 2*i+1;
if(k+1<v.size())
k+= int(v[k]>v[k+1]);
if(v[i]>v[k]){
swap(v[i], v[k]);
heapify(k, v);
}
}
void build_heap(vector<ll> &v)
{
if(v.empty())
return;
int i=(v.size()+1)/2;
while(i--)
heapify(i, v);
}
void insert(ll n, vector<ll> &v)
{
if(v.empty())
return;
v.push_back(n);
int i=v.size()-1;
while(i && v[(i-1)/2]>v[i])
{
swap(v[i], v[(i-1)/2]);
i=(i-1)/2;
}
}
ll extract_min(vector<ll> &v)
{
if(v.empty())
return -1;
ll min=v[0];
v[0]=v.back();
v.pop_back();
heapify(0, v);
return min;
}
ll find_min(const vector<ll> v){
return v.empty()?-1:v[0];
}
vector<ll> heap_sort(vector<ll> v)
{
vector<ll> w;
w.reserve(v.size());
build_heap(v);
while(!v.empty())
w.push_back(extract_min(v));
return w;
}
int main()
{
//driver code
vector<ll> v = {12, 11, 13, 5, 6, 7};
for(auto i : v)
cout<<i<<" ";
v=heap_sort(v);
cout<<"\nSorted array is \n";
for(auto i : v)
cout<<i<<" ";
cout<<endl;
return 0;
}