Skip to content

Instantly share code, notes, and snippets.

@dougyoung
Created January 5, 2018 21:57
Show Gist options
  • Save dougyoung/6ab18ec3aae962bc949eff891965b46a to your computer and use it in GitHub Desktop.
Save dougyoung/6ab18ec3aae962bc949eff891965b46a to your computer and use it in GitHub Desktop.
Implementation of an integer min heap in Python3, O(n*log(n)) time.
# TODO: Should make this an object for sharing.
heap = []
def hasParent(index):
return parentIndex(index) >= 0 and parentIndex(index) < len(heap)
def hasLeftChild(index):
return leftChildIndex(index) < len(heap)
def hasRightChild(index):
return rightChildIndex(index) < len(heap)
def parent(index): return heap[parentIndex(index)]
def leftChild(index): return heap[leftChildIndex(index)]
def rightChild(index): return heap[rightChildIndex(index)]
def parentIndex(index): return (index-1)//2
def leftChildIndex(index): return (index*2)+1
def rightChildIndex(index): return (index*2)+2
def value(index):
if index > len(heap): raise "Index off bounds of heap!"
return heap[index];
def add(value):
heap.append(value)
heapifyUp()
def remove(value):
index = heap.index(value)
heap[index] = heap[len(heap)-1]
heap.remove(heap[len(heap)-1])
heapifyDown(index)
def min():
if len(heap) == 0: raise "Nothing in the heap!"
return heap[0]
def swap(indexOne, indexTwo):
temp = heap[indexOne]
heap[indexOne] = heap[indexTwo]
heap[indexTwo] = temp
def heapifyDown(index):
if len(heap) == 0: return
currentIndex = index
while (hasLeftChild(currentIndex)):
minNodeIndex = leftChildIndex(currentIndex)
if hasRightChild(currentIndex) and rightChild(currentIndex) < leftChild(currentIndex):
minNodeIndex = rightChildIndex(currentIndex)
if minNodeIndex < value(currentIndex):
swap(currentIndex, minNodeIndex)
currentIndex = minNodeIndex
else:
break
def heapifyUp():
if len(heap) == 0: return
currentIndex = len(heap)-1
while hasParent(currentIndex):
if value(currentIndex) > parent(currentIndex): break;
swap(currentIndex, parentIndex(currentIndex))
currentIndex = parentIndex(currentIndex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment