Skip to content

Commit

Permalink
add heap
Browse files Browse the repository at this point in the history
  • Loading branch information
SKTT1Ryze committed Mar 14, 2024
1 parent 772ff65 commit 19f0084
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
21 changes: 21 additions & 0 deletions leetcode-cc/Heap.cc
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
}
34 changes: 34 additions & 0 deletions leetcode-cc/Heap.h
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();
};

0 comments on commit 19f0084

Please sign in to comment.