This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
DSA/\
2019-03-27 23:01:13 +01:00

77 lines
1.4 KiB
Python

#!/usr/bin/env python3
import sys
def heap_extract_max(A):
m = A[0]
A[0] = A.pop()
size = len(A)
i = 0
exit = not size == 0
while exit:
left = heap_left(size, i)
print("left =", left)
if left == None:
break
right = heap_right(size, i)
print("right =", right)
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:]]
print(args)
print(heap_extract_max(args))
print(args)