class helem: def __init__(self, k = 0, v = 0): self.key = k self.val = v def push(heap, el): i = len(heap) heap.append(el) while i > 1 and el.key > heap[int(i/2)].key: heap[i] = heap[int(i/2)] i = int(i/2) heap[i] = el def pop(heap): if len(heap) < 2: return heap[0], heap item = heap[1] last = heap[len(heap)-1] heap = heap[0:len(heap)-1] parent = 1 child = 2 while child < len(heap): if child < len(heap)-1 and \ heap[child].key < heap[child+1].key: child += 1 if last.key > heap[child].key: break heap[parent] = heap[child] parent = child child *= 2 if len(heap) > 1: heap[parent] = last return item, heap
Разукрашено на tohtml.com