tvl-depot/users/wpcarro/scratch/facebook/heap.py
Vincent Ambo 019f8fd211 subtree(users/wpcarro): docking briefcase at '24f5a642'
git-subtree-dir: users/wpcarro
git-subtree-mainline: 464bbcb15c
git-subtree-split: 24f5a642af
Change-Id: I6105b3762b79126b3488359c95978cadb3efa789
2021-12-14 02:15:47 +03:00

30 lines
707 B
Python

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)