diff options
author | William Carroll <wpcarro@gmail.com> | 2020-11-14T14·08+0000 |
---|---|---|
committer | William Carroll <wpcarro@gmail.com> | 2020-11-14T14·08+0000 |
commit | 47c5c6ac05e7c42d7586d7248a2ec175b91b620e (patch) | |
tree | 6dc79e1689514b573da0ec7a2264d305dacbb93f /scratch/facebook/heap.py | |
parent | c841527f616ffb4a6cd64f941421cf42f54b7d00 (diff) |
Partially implement a Heap
Defining the insert (or "siftup") function described in the "Programming Pearls" book.
Diffstat (limited to 'scratch/facebook/heap.py')
-rw-r--r-- | scratch/facebook/heap.py | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/scratch/facebook/heap.py b/scratch/facebook/heap.py new file mode 100644 index 000000000000..0c0dce91b4dd --- /dev/null +++ b/scratch/facebook/heap.py @@ -0,0 +1,30 @@ +from math import floor + +class Heap(object): + def __init__(self): + self.xs = [None] + self.i = 1 + + def __repr__(self): + return "[{}]".format(", ".join(str(x) for x in self.xs[1:])) + + def insert(self, x): + if len(self.xs) == 1: + self.xs.append(x) + self.i += 1 + return + self.xs.append(x) + i = self.i + while i != 1 and self.xs[floor(i / 2)] > self.xs[i]: + self.xs[floor(i / 2)], self.xs[i] = self.xs[i], self.xs[floor(i / 2)] + i = floor(i / 2) + self.i += 1 + + def root(self): + return self.xs[1] + +xs = Heap() +print(xs) +for x in [12, 15, 14, 21, 1, 10]: + xs.insert(x) + print(xs) |