126 lines
2.2 KiB
Python
Executable file
126 lines
2.2 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
import math
|
|
|
|
def heap_sort(A):
|
|
heap_build_max_heap(A)
|
|
|
|
print("Initial heap:")
|
|
heap_print(A, len(A))
|
|
print()
|
|
|
|
for i in range(len(A)-1, 0, -1):
|
|
A[0], A[i] = A[i], A[0]
|
|
heap_max_heapify(A, i)
|
|
|
|
print("\nNew heap: length =", i)
|
|
heap_print(A, i)
|
|
print()
|
|
|
|
def heap_max_heapify(A, size):
|
|
if size < 2:
|
|
return
|
|
|
|
print("size =", size)
|
|
i = 0
|
|
|
|
left = heap_left(size, i)
|
|
print("left =", left)
|
|
|
|
while left is not None:
|
|
right = heap_right(size, i)
|
|
print("right =", right)
|
|
|
|
if right is None:
|
|
if A[i] < A[left]:
|
|
A[i], A[left] = A[left], A[i]
|
|
break
|
|
|
|
ma = max_3(A[i], A[left], A[right])
|
|
if ma == A[i]:
|
|
break
|
|
elif ma == A[left]:
|
|
A[i], A[left] = A[left], A[i]
|
|
i = left
|
|
else:
|
|
A[i], A[right] = A[right], A[i]
|
|
i = right
|
|
|
|
left = heap_left(size, i)
|
|
print("left =", left)
|
|
|
|
|
|
def heap_build_max_heap(A):
|
|
if len(A) < 2:
|
|
return
|
|
for i in range(math.ceil(len(A)/2), 1, -1):
|
|
heap_max_heapify(A, i)
|
|
|
|
|
|
def heap_print(A, size):
|
|
i = 1
|
|
newline = False
|
|
while i <= size:
|
|
print(A[i-1], end='\t')
|
|
newline = False
|
|
i = i + 1
|
|
if is_power_2(i):
|
|
print()
|
|
newline = True
|
|
if not newline:
|
|
print()
|
|
|
|
|
|
def is_power_2(n):
|
|
while n > 1:
|
|
if n % 2 == 1:
|
|
return False
|
|
n = n // 2
|
|
return True
|
|
|
|
|
|
def max_3(a, b, c):
|
|
if a > b:
|
|
if a > c:
|
|
return a
|
|
else:
|
|
return c
|
|
else:
|
|
if b > c:
|
|
return b
|
|
else:
|
|
return c
|
|
|
|
|
|
def heap_parent(n):
|
|
n = n + 1
|
|
if n == 1:
|
|
return None
|
|
else:
|
|
return (n // 2) - 1
|
|
|
|
|
|
def heap_left(size, n):
|
|
n = n + 1
|
|
l = n * 2
|
|
if l > size:
|
|
return None
|
|
else:
|
|
return l - 1
|
|
|
|
|
|
def heap_right(size, n):
|
|
n = n + 1
|
|
l = n * 2 + 1
|
|
if l > size:
|
|
return None
|
|
else:
|
|
return l - 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
args = [int(x) for x in sys.argv[1:]]
|
|
heap_sort(args)
|
|
print(args)
|
|
|