최대 히프
우선 순위 Queue 삽입은 일반적인 queue와 같으나, 삭제는 우선 순위가 가장 높은 것이 먼저 삭제 최대(최소) Heap는 최대(최소) 우선 순위 Queue를 구현하는데 사용 Heap 완전이진트리 → 1차원 배열 사
dyeoma.tistory.com
최대 히프 class
class MaxHeap {
...
private:
Element<Type> *heap;
int n; // 히프 현재 크기
int MaxSize; // 히프 최대 크기
}
최대 히프 생성자
MaxHeap::MaxHeap (int size=DefaultSize){
MaxSize = size; n=0;
heap = new Element<Type>[MaxSize + 1]; // heap[0]은 미사용
}
최대 히프 삽입 함수 - O(log_2(n)) 소요 [ log_2(n) = 완전이진트리 높이 ]
template <class Type>
void MaxHeap<Type>::Insert(const Element<Type> &x){
int i;
if (n==MaxSize) { // full이면 크기 확장
HeapFull();
return;
}
n++;
for(i=n; 1; ){
if(i==1) // root node
break;
if(x.key <= heap[i/2].key)
break;
// parent -> child
heap[i] = heap[i/2];
i/=2;
}
heap[i] = x;
}
최대 히프 삭제 함수 - O(log_2(n)) 소요 [ log_2(n) = 완전이진트리 높이 ]
template <class Type>
Element<Type> *MaxHeap<Type>::DeleteMax (Element<Type> &x){
// 최대히프 삭제
int i;
if(!n) // empty heap
return 0;
x = heap[1];
Element<Type> k = heap[n];
n--;
for (i=1, int j=2; j<=n; ){
// j는 값이 더 큰 child
if (j<n)
if (heap[j].key < heap[j+1].key)
j++;
if(k.key >= heap[j].key)
break;
// child를 parent로 이동
heap[i] = heap[j];
// i,j child로 이동
i=j; j*=2;
}
heap[i]=k;
return &x;
}
'알고리즘 > C++' 카테고리의 다른 글
9. 그래프 (Graph) (0) | 2020.07.26 |
---|---|
8. 이진 탐색 트리 (Binary Search Tree, BST) (0) | 2020.07.25 |
6. 트리 (Tree) (0) | 2020.07.24 |
5-1. 이중 연결 리스트 (Doubly Linked List) (0) | 2020.07.24 |
4-1. 연결 큐 (Linked Queue) (0) | 2020.07.24 |