Last active
September 28, 2017 11:59
-
-
Save thundergolfer/b850ea6ea479d47ed05e1959360fa3c5 to your computer and use it in GitHub Desktop.
A binary heap implementation that I wrote, and am thus more familiar with.
This file contains hidden or 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
class Heap(): | |
def __init__(self): | |
self.data = [None] | |
self.size = 0 | |
def insert(self, n): | |
self.size += 1 | |
self.data.append(n) | |
self._swim(self.size) | |
def pop(self): | |
self._swap(1, self.size) | |
popped = self.data[self.size] | |
del self.data[self.size] | |
self.size -= 1 | |
self._sink(1) | |
return popped | |
def display(self): | |
data = self.data[1:] | |
N = len(data) | |
for i, elem in enumerate(data): | |
j = 0 | |
while(j < (2 ** i) and j + (2 ** i) < N): | |
print(data[j + (2 ** i) - 1], " ", end='') | |
j += 1 | |
print() | |
def __contains__(self, n): | |
k = 1 | |
curr_lvl = 0 | |
while k < self.size: | |
lo, hi = 2 ** curr_lvl, min(2 ** (curr_lvl + 1) - 1, self.size - 1) | |
for i in range(lo, hi): | |
if n == self.data[i]: | |
return True | |
else: | |
if n > self.data[hi]: | |
print("breaking out early at: ", self.data[hi]) | |
return False | |
k = hi | |
curr_lvl += 1 | |
return False | |
def _swim(self, k): | |
while(k > 1 and self._less(k // 2, k)): | |
self._swap(k, k // 2) | |
k //= 2 | |
def _sink(self, k): | |
while(2 * k <= self.size): | |
j = 2 * k | |
if j < self.size and self._less(j, j + 1): | |
j += 1 | |
if not self._less(k, j): | |
break | |
self._swap(k, j) | |
k = j | |
def _swap(self, i, j): | |
temp = self.data[i] | |
self.data[i] = self.data[j] | |
self.data[j] = temp | |
def _less(self, i, j): | |
return self.data[i] < self.data[j] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment