class HeapArray:
def __init__(self):
self._data = []
self._size = 0
def __str__(self):
return str(self._data)
def is_empty(self):
return self._size == 0
def insert(self,num):
index = self._size
self._data.insert(index,num) #cound have used .append(num)
while index > 0 and self._data[index] < self._data[(index-1)//2]:
temp = self._data[index]
self._data[index] = self._data[(index-1)//2]
self._data[(index-1)//2] = temp
index = (index-1)//2
self._size = self._size + 1
def delete_min(self):
if self._size == 0:
return None
elif self._size == 1:
self._size = 0
return self._data.pop(0)
else:
min = self._data[0]
self._data[0] = self._data.pop(self._size-1)
self._size = self._size - 1
index = 0
while 2*index+1 < self._size:
if 2*index+2 < self._size: # 2 children
if self._data[index] < self._data[2*index+1] and \
self._data[index] < self._data[2*index+2]:
break
if self._data[2*index+1] < self._data[2*index+2]:
temp = self._data[index]
self._data[index] = self._data[2*index+1]
self._data[2*index+1] = temp
index = 2*index+1
else:
temp = self._data[index]
self._data[index] = self._data[2*index+2]
self._data[2*index+2] = temp
index = 2*index+2
else: # one child
if self._data[index] > self._data[2*index+1]:
temp = self._data[index]
self._data[index] = self._data[2*index+1]
self._data[2*index+1] = temp
index = 2*index+1
else:
break
return min