import heapq
import numpy as np
def MakeHeap(a):
for i in range(int(a.size / 2) - 1, -1, -1):
AdjustHeap(a, i, a.size)
def AdjustHeap(a, i, n):
j = i*2 +1
x = a[i]
while j < n:
if j + 1 < n and a[j+1] < a[j]:
j += 1
if a[j] >= x :
break
a[i], a[j] = a[j], a[i]
i = j
j = i*2 + 1
def HeapSort(a):
MakeHeap(a)
for i in range(a.size - 1,0, -1):
a[i], a[0] = a[0], a[i]
AdjustHeap(a, 0, i)
if __name__ == '__main__':
a = np.random.randint(0, 100, size = 10)
print ("Before sorting...")
print ("---------------------------------------------------------------")
print (a)
print ("---------------------------------------------------------------")
a1=a
HeapSort(a1)
print ("After sorting...")
print ("---------------------------------------------------------------")
print (a1[::-1] )
print(a1)
print( "---------------------------------------------------------------")
b=list(a)
heapq.heapify(b)
heap = []
while b:
heap.append(heapq.heappop(b))
b[:] = heap
print ('-------------------------------------------------')
print ('sdk sorted',b)
[92 97 3 60 8 67 13 65 35 94]
---------------------------------------------------------------
After sorting...
---------------------------------------------------------------
[ 3 8 13 35 60 65 67 92 94 97]
[97 94 92 67 65 60 35 13 8 3]
sdk sorted [3, 8, 13, 35, 60, 65, 67, 92, 94, 97]