void push(int data) {
// 힙의 가장 끝에 데이터 추가
heap[++heap_count] = data;
// 아래의 과정은 child를 parent와 비교하면서 알맞은 위치로 하나씩 올리는 부분
int child = heap_count;
int parent = child / 2;
while (child > 1 && heap[parent] < heap[child]) {
swap(&heap[parent], &heap[child]);
child = parent;
parent = child / 2;
}
}
int pop() {
// 힙의 가장 첫번째 원소를 반환
// 힙의 가장 앞만 보고 있다!
int result = heap[1];
// 첫번째 원소를 힙의 가장 끝에 원소와 바꾸고
// 가장 끝은 이제 쓰지 않을 예정이니 heap_count를 내려준다.
swap(&heap[1], &heap[heap_count]);
heap_count--;
// 아래의 과정은 child를 parent와 비교하면서 알맞은 위치로 하나씩 내리는 부분
int parent = 1;
int child = parent * 2;
if (child + 1 <= heap_count) {
child = (heap[child] > heap[child + 1]) ? child : child + 1;
}
while (child <= heap_count && heap[parent] < heap[child]) {
swap(&heap[parent], &heap[child]);
parent = child;
child = child * 2;
if (child + 1 <= heap_count) {
child = (heap[child] > heap[child + 1]) ? child : child + 1;
}
}
return result;
}
https://gmlwjd9405.github.io/2018/05/10/data-structure-heap.html
https://www.geeksforgeeks.org/heap-data-structure/
https://twpower.github.io/137-heap-implementation-in-cpp