-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinaryheap.cpp
More file actions
83 lines (65 loc) · 1.26 KB
/
binaryheap.cpp
File metadata and controls
83 lines (65 loc) · 1.26 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
#include <iostream>
#include <algorithm>
#include "binaryheap.h"
void binaryheap::heapup(int i)
{
int p=parent(i);
if(i<vec.size() && p>=0 && (*vec[i]< *vec[p]))
{
std::swap(vec[p],vec[i]);
heapup(p);
}
}
void binaryheap::heapdown(int i){
int left=lchild(i);
int right=rchild(i);
int smallest=i; /* cited from the CLRS Textbook on binary heap */
if(smallest!=i)
{
std::swap(vec[i],vec[smallest]);
heapdown(smallest);
}
if(left<vec.size() && (*(vec[left])< *(vec[smallest])))
{
smallest=left;
}
if(right<vec.size() && (*(vec[right]) < *(vec[smallest])))
{
smallest=right;
}
}
void binaryheap::insert(node_huffman const* newele){
vec.push_back(newele);
heapup(vec.size()-1);
}
void binaryheap::remove_min(){
int len=vec.size()-1;
if(len>=0){
vec[0]=vec[len];
vec.pop_back();
heapdown(0);
}
}
node_huffman const* binaryheap::minextract(){
if(vec.size()==0){
return NULL;
}
return vec[0];
}
binaryheap::binaryheap(std::vector<node_huffman const*> &nodes_hufftree){
for(node_huffman const * node:nodes_hufftree){
insert(node);
}
}
int binaryheap::parent(int i){
return (i-1)/2;
}
int binaryheap::lchild(int i){
return 2*i+1;
}
int binaryheap::rchild(int i){
return 2*i+2;
}
int binaryheap::size(){
return vec.size();
}