-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.cpp
More file actions
71 lines (64 loc) · 1.2 KB
/
Heap.cpp
File metadata and controls
71 lines (64 loc) · 1.2 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
/// heap implemantation
#include <iostream>
using namespace std;
int heap[1005],len=0;
int getParentIndex(int index){
return index/2;
}
int getParent(int index){
return heap[index/2];
}
void heapifyup(){
int index=len-1;
while(index && getParent(index)<heap[index]){
swap(heap[index],heap[getParentIndex(index)]);
index = getParentIndex(index);
}
}
void add(int value){
if(len==0){
heap[0]=value;
len++;
}
else{
heap[len]=value;
len++;
heapifyup();
}
}
int getLeft(int i){
return i*2+1;
}
int getRight(int i){
return i*2+2;
}
void heapifydown(){
int index=0,largest;
while(1){
int left=getLeft(index);
int right=getRight(index);
if(left >= len)
break;
if(heap[index]<heap[left])
largest=left;
else
largest=index;
if(right <len && heap[largest]<heap[right])
largest=right;
if(largest==index)
break;
swap(heap[index],heap[largest]);
index=largest;
}
}
int Remove(){
int ret=heap[0];
heap[0]=heap[len-1];
len--;
heapifydown();
return ret;
}
int main()
{
return 0;
}