class Heap:
def __init__(self):
self.values = []
self.size = 0
def Insert(self, x):
self.values.append(x)
self.size += 1
self.SwitchUp(self.size - 1)
def SwitchUp(self, i):
while i != 0 and self.values[i] <= self[(i - 1)// 2]:
self.values[i], self[(i - 1)// 2] = self[(i - 1)// 2], self.values[i]
i =(i - 1)// 2
def ExtractMin(self):
if not self.size:
return None
tmp = self.values[0]
self.values[0] = self.values[-1]
self.values.pop()
self.size -= 1
self.SwitchDown(0)
return tmp
def SwitchDown(self, i):
while 2*i+1 < self.size:
if self.values(2*i+1) < self.values(i):
j = 2*i + 1
if 2*i + 2 < self.size and self.values(2*i + 2) < self.values(2*i + 1):
j = 2*i + 2
if i == j:
break
self.values[i], self.values[j] = self.values[j], self.values[i]
i = j
def heaphy(iterable):
heap = Heap()
for item in iterable:
heap.Insert(item)
return heap
def Get_sorted_arr(heap):
arr = []
while heap.size:
arr.append(heap.ExtractMin())
G = [7, 8, 5, 67, 21, 54, 1]
heaphy(G)
Get_sorted_arr(heap)