-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.h
121 lines (101 loc) · 2.13 KB
/
Heap.h
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
120
121
#ifndef Heap_H
#define Heap_H
#include "Darray.h"
template<class T>
class Heap
{
public:
Heap<T> (bool (*comp)(T obj1, T obj2));
bool isEmpty();
void push(T obj);
void pop();
T top();
private:
bool (*compare)(T obj1, T obj2);
Darray<T> heap;
void UpnUp(int idx);
void DownnDown(int idx);
int leftChild(int i)
{
return 2*i + 1;
}
int rightChild(int i)
{
return 2*i + 2;
}
int parent(int i)
{
return (i-1)/2;
}
};
template<class T> Heap<T>::Heap(bool (*comp)(T obj1, T obj2))
{
this -> compare = comp;
}
template<class T> bool Heap<T>::isEmpty()
{
return heap.empty();
}
template<class T> void Heap<T>::push(T obj)
{
heap.push_back(obj);
UpnUp(heap.size()-1);
}
template<class T> void Heap<T>::pop()
{
if(!isEmpty())
{
std::swap(heap[0], heap[heap.size()-1]);
heap.pop_back();
if(!isEmpty())
DownnDown(0);
}
else
{
throw std::invalid_argument( "heap is empty" );
}
}
template<class T> T Heap<T>::top()
{
if(!isEmpty())
{
return heap[0];
}
else
{
throw std::invalid_argument( "heap is empty" );
}
// return throw invalid_argument( "heap is empty" );
}
template<class T> void Heap<T>::DownnDown(int idx)
{
int largeIdx = idx;
int leftChildIdx = leftChild(idx), rightChildIdx = rightChild(idx);
if(leftChildIdx < heap.size())
{
if(compare(heap[largeIdx], heap[leftChildIdx]))
largeIdx = leftChildIdx;
}
if(rightChildIdx < heap.size())
{
if(compare(heap[largeIdx], heap[rightChildIdx]))
largeIdx = rightChildIdx;
}
if(largeIdx != idx)
{
std::swap(heap[largeIdx], heap[idx]);
DownnDown(largeIdx);
}
}
template<class T> void Heap<T>::UpnUp(int idx)
{
int parentIdx = parent(idx);
if(parentIdx < 0)
return;
if(compare(heap[parentIdx], heap[idx]))
{
std::swap(heap[parentIdx], heap[idx]);
UpnUp(parentIdx);
}
}
#endif