O(1)의 시간복잡도가 소요 (장점)O(n)의 시간복잡도가 소요 (단점)O(n)의 시간복잡도가 소요 (단점)O(1)의 시간복잡도가 소요 (장점)앞선 Array와 Sorted Array에서의 장단점은 Linked List와 Sorted Linked List에서 동일하게 작용
O(log₂n)의 시간 복잡도를 가지므로 앞선 구현 방식에 비해 노드의 개수가 많아질수록 유리root노드는 배열의 1번에 저장됨부모, 자식 노드의 인덱스 계산
현재 인덱스
i
부모 노드의 인덱스 :i/2
왼쪽 자식 노드의 인덱스 :i* 2
오른쪽 자식 노드의 인덱스 :i* 2 + 1
h는 log₂n이므로 삽입의 시간 복잡도는 O(log₂n) void insert(int key)
{
if (isFull()) return; // When the heap is full
int i = ++size; // Start from the position corresponding to the incremented heap size
// Traverse upward through the tree, comparing with parent nodes
// While the key is greater than the parent
while (i != 1 && key > getParent(i).getKey())
{
node[i] = getParent(i).getKey() ; // Move the parent node down
i /= 2; // Move up one level
}
node[i].setKey(key); // Final position: copy the data
}
root가 아니고 부모 노드의 값보다 크다면 현재 위치에 부모 노드의 값을 저장하고 윗 레벨로 이동root를 제거하므로)O(log₂n)의 시간 복잡도를 가짐 HeapNode remove() {
if( isEmpty() ) return NULL;
HeapNode root = node[1]; // Root node (the element to be removed)
HeapNode last = node[size--]; // The last node in the heap
int parent = 1; // Start Index
int child = 2; // Start Index's child(left)
while( child <= size ) // While not exceeding the heap boundary
{
if( child < size
&& getLeft(parent).getKey() < getRight(parent).getKey())
child++; // Select the larger child node
if( last.getKey() >= node[child].getKey() ) break;
// Move down one level
node[parent] = node[child];
parent = child;
child *= 2;
}
node[parent] = last; // Place the last node in its final position
return root; // Return the root node
}
root 노드의 값을 root에, 마지막 노드의 값을 last에 저장root 노드는 1에서 시작하므로 parent는 1을 갖고 child는 왼쪽 Subtree를 기준으로 하여 2로 설정while문 내부 로직을 반복child를 설정할 때 더 큰 자식 노드를 선택하기 위해 오른쪽 자식 노드가 더 크다면 기존 child 값에 1을 더함last 노드에 저장된 값이 선택된 자식 노드의 값보다 크거나 같다면 반복을 종료