Heap
μ μ
ꡬν(Python) - Max Heap
HEAP_SIZE = 0 # νμ μ‘΄μ¬νλ μμμ κ°μλ₯Ό μ μ₯ν λ³μ
heap = [None] # ν (0λ² μΈλ±μ€ λ―Έμ¬μ©)μ½μ
# νμ μ½μ
μ. λ°λ³΅ μΈλ±μ€ iλ λ°©κΈ λ€μ΄κ° λ°μ΄ν°μ μΈλ±μ€λΆν° 루νΈμ μμκΉμ§
# 1. λ§μ§λ§ λ
Έλμ μ λ°μ΄ν°λ₯Ό μ½μ
# 2. (μ΅λ ν κΈ°μ€) λΆλͺ¨μ λΉκ΅ν΄μ λΆλͺ¨λ³΄λ€ ν¬λ©΄ λΆλͺ¨μ swap
# 3. λΆλͺ¨κ° λ ν° κ°μΌ λκΉμ§ 2λ²μ λ°λ³΅
def push(data):
global HEAP_SIZE
HEAP_SIZE += 1
heap.append(data)
i = HEAP_SIZE
while i > 1:
parent = i//2
if heap[i] <= heap[parent]:
break
heap[i], heap[parent] = heap[parent], heap[i]
i = parentμμ
μκ°λ³΅μ‘λ
Last updated