-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
#include "Heap.h" | ||
|
||
template <typename T> | ||
void Heap<T>::insert(T value) { | ||
inner.push_back(value); | ||
floatUp(inner.size() - 1); | ||
} | ||
|
||
template <typename T> | ||
void Heap<T>::pop() { | ||
if (!inner.empty()) { | ||
std::swap(inner[0], inner[inner.size() - 1]); | ||
inner.pop_back(); | ||
sinkDown(0); | ||
} | ||
} | ||
|
||
template <typename T> | ||
T Heap<T>::top() { | ||
return inner[0]; // panic if inner is empty | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
#include <memory.h> | ||
|
||
#include <vector> | ||
|
||
template <typename T> | ||
class Heap { | ||
private: | ||
std::vector<T> inner; | ||
|
||
void floatUp(int index) { | ||
while (index > 0 && inner[index] > inner[(index - 1) / 2]) { | ||
std::swap(inner[index], inner[(index - 1) / 2]); | ||
index = (index - 1) / 2; | ||
} | ||
} | ||
void sinkDown(int index) { | ||
int n = inner.size(); | ||
while (index * 2 + 1 < n) { | ||
int child = index * 2 + 1; | ||
if (child + 1 < n && inner[child + 1] > inner[child]) child++; | ||
if (inner[index] < inner[child]) { | ||
std::swap(inner[index], inner[child]); | ||
index = child; | ||
} else { | ||
break; | ||
} | ||
} | ||
} | ||
|
||
public: | ||
void insert(T value); | ||
void pop(); | ||
T top(); | ||
}; |