I am working on an application that demonstrates the Djikstra\'s algorithm, and to use it, I need to restore the heap property when my elements\' value is decreased
I had implemented the same thing. In the MinHeap class, I had added a dictionary that is used to access the item in O(1). And on decrease key, it will be bubbled up in O(logn) time.
class MinHeap:
def __init__(self, array):
self.heap = self.buildHeap(array)
self.idx_of_element = {}
def getParentIdx(self, idx):
return (idx - 1) // 2
def getLeftChildIdx(self, idx):
return idx * 2 + 1
def getRightChildIdx(self, idx):
return idx * 2 + 2
def buildHeap(self, array):
# Write your code here.
lastIdx = len(array) - 1
startFrom = self.getParentIdx(lastIdx)
for i in range(startFrom, -1, -1):
self.siftDown(i, array)
return array
# this is min-heapify method
def siftDown(self, idx, array):
while True:
l = self.getLeftChildIdx(idx)
r = self.getRightChildIdx(idx)
smallest = idx
if l < len(array) and array[l] < array[idx]:
smallest = l
if r < len(array) and array[r] < array[smallest]:
smallest = r
if smallest != idx:
array[idx], array[smallest] = array[smallest], array[idx]
self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[smallest]] = self.idx_of_element[self.heap[smallest]], self.idx_of_element[self.heap[idx]]
idx = smallest
else:
break