max_heap: A[0]
is the maximum value
min_heap: A[0]
is the minimum value
source code: AC/Algorithms/Heap
intro
go_up(int i)
: from node i go up to at most node 0, swap with parent if node i is bigger (time: $O(log(n))$)go_down(int i)
: from node i go down to its leaf child at most, swap with the larger child every time goes down (time: $O(log(n))$)heapify(n)
: adjustA[0..n-1]
as a heap withgo_down
(time: $O(n)$, refer: How is make_heap in C++ implemented to have complexity of 3N?)push(int x)
:A[sz] = x
, thengo_up(sz++)
(time: $O(log(n))$, same asgo_up
)pop()
:swap(A[0], A[--sz])
, thengo_down(0)
(time: $O(log(n))$, same asgo_down
)
code
complete source code on github
|
|
Refs
- How is make_heap in C++ implemented to have complexity of 3N?
- STL source code: make_heap, push_heap, pop_heap, …