복습)
Initialization : It is true prior to the first iteration of the loop.
Maintenance : If it is true before an iteration of the loop, it remains true before the next iteration.
Termination : When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
Build-Max-Heap의 Loop Invariant
At the start of each iteration of the for loop, each node i+1, i+2, ..., n-1, n is the root of a max-heap.
Initialization
Maintenance
Termination
height : 그 노드에서 아래로 내려가 리프에 도달하는 가장 긴 경로의 간선 수
depth : 루트에서부터의 거라. level이라고도 함.
-> 중간에 +1을 넣어서 ceil fn을 벗겨내는 디테일 좋다.
따라서, Build max heap의 upper bound를 더욱 타이트하게 잡아보면
O(nlog(n))에서 O(n)까지 만들 수 있다.
Let's assume the tree is Complete binary tree.
그러면 노드의 총 개수 n은 2^h - 1개가 된다.
- 높이가 h인 노드의 개수는 1개이며, 이 노드에서 max heapify는 최악의 경우 h만큼 내려간다.
- 높이가 h-1인 노드의 개수는 2개이며, 이 노드에서는 h-1만큼 내려간다.
...- 이를 식으로 표현해보면
cost S = h + 2(h-1) + 2^2(h-2) + 2^3*(h-3) + ... + 2^(h-1)*(1) + 2^h*0
2S = 2h + 2^2(h-1) + 2^3(h-2) + ... + 2^h(1)
...
S = 2*2^(log(n)) - log(n) - 2 <= 2n
MAX_HEAP_INCREASE_KEY(A, i, key)
if (key < A[i])
return "new key is smaller than current key"
A[i] = key
while i > 1 && A[parent(i)] < A[i]
exchange(A[parent(i)], A[i])
i = parent(i)
MAX_HEAP_INSERT(A, key)
A.heap-size = A.heap-size + 1
A[heap-size] = -Inf
MAX_HEAP_INCREASE_KEY(A, A.heap-size, key)