72 lines
1.2 KiB
Python
Executable file
72 lines
1.2 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
|
|
import sys
|
|
|
|
def heap_extract_max(A):
|
|
m = A[0]
|
|
A[0] = A.pop()
|
|
|
|
size = len(A)
|
|
i = 0
|
|
exit = size == 0
|
|
while exit:
|
|
left = heap_left(i)
|
|
if left == None:
|
|
break
|
|
|
|
right = heap_right(i)
|
|
if right == 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
|
|
|
|
return m
|
|
|
|
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:]]
|
|
|