-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryheap.cpp
More file actions
119 lines (104 loc) · 1.95 KB
/
binaryheap.cpp
File metadata and controls
119 lines (104 loc) · 1.95 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "bits/stdc++.h"
using namespace std;
template<typename T, typename C = less<T> > class Heap{
vector<T> *heap;
public:
Heap(vector<T> *arr){
heap = new vector<T> (arr->begin(), arr->end());
build_heap();
}
void build_heap(){
size_t n = heap->size()-1;
for (int i=(n-1)/2; i>=0; i--){
shiftDown(i);
}
}
void print(){
for (auto &i: *heap){
cout<<i<<" ";
}
cout<< endl;
}
void shiftDown(int i){
while(2*i+1 < heap->size()){
int child = 2*i+1;
if(child+1 < heap->size()){
if( C()(heap->at(child+1),heap->at(child)) ){
child++;
}
}
if( C()(heap->at(child), heap->at(i)) ){
swap(heap->at(child), heap->at(i));
i = child;
}
else
break;
}
}
void shiftUp(int i){
while(i > 0 ){
int par = (i-1)/2;
if( C()(heap->at(i), heap->at(par)) ){
swap(heap->at(par), heap->at(i));
i = par;
}
else
break;
}
}
void sort(){
int size = heap->size()-1;
while(size>0){
swap(heap->at(0), heap->at(size));
size--;
int t = 0;
while(t <= size){
int child = t*2 +1;
if(child > size)
break;
if( child+1 <= size and C()( heap->at(child+1), heap->at(child)) ){ // <--- took 2 days
child++;
}
if(C()( heap->at(child), heap->at(t))){
swap(heap->at(t), heap->at(child));
t = child;
}
else{
break;
}
}
}
}
T top(){
return heap->size()?heap->front(): NULL;
}
void push(T var){
heap->push_back(var);
int ind = heap->size()-1;
shiftUp(ind);
}
T pop(){
if(heap->size()==0)
return NULL;
int ind = heap->size()-1;
swap(heap->at(0),heap->at(ind));
heap->pop_back();
if(heap->size()>1)
shiftDown(0);
}
};
int main(){
vector<int> v={8, 7, 6, 5, 4, 3, 2, 1};
for (int ij=10; ij>0; ij--)
v.push_back(ij+10);
Heap<int, greater<int>> heap(&v);
heap.print();
heap.sort();
heap.print();
cout<<endl;
Heap<int> heap2(&v);
heap2.print();
heap2.sort();
heap2.print();
return 0;
}