Heap
- 출처: https://st-lab.tistory.com/205#클래스
- 최솟값 또는 최댓값을 빠르게 찾아내기 위해 완전이진트리 형태로 만들어진 자료구조
- 부모 노드는 항상 자식 노드보다 우선순위가 높음
- 최소 힙 : 부모 노드의 값(key 값) ≤ 자식 노드의 값(key 값)
- 최대 힙 : 부모 노드의 값(key 값) ≥ 자식 노드의 값(key 값)
- 시간 복잡도
O(NlogN)
- 트리 구조를 배열로 구현
- 구현의 용이함을 위해 시작 인덱스(root)는 1 부터 시작
- 각 노드와 대응되는 배열의 인덱스는 불변
- [성질]
- 왼쪽 자식 노드 인덱스 = 부모 노드 인덱스 × 2
- 오른쪽 자식 노드 인덱스 = 부모 노드 인덱스 × 2 + 1
- 부모 노드 인덱스 = 자식 노드 인덱스 / 2
우선순위 큐(Priority Queue)
Java 에서의 java.util.PriorityQueue
import java.util.PriorityQueue;
import java.util.Collections;
PriorityQueue<Integer> priorityQueueLowest = new PriorityQueue<>();
PriorityQueue<Integer> priorityQueueHighest = new PriorityQueue<>(Collections.reverseOrder());
priorityQueueLowest.add(1);
priorityQueueLowest.add(10);
priorityQueueLowest.offer(100);
priorityQueueHighest.add(1);
priorityQueueHighest.add(10);
priorityQueueHighest.offer(100);
priorityQueueLowest.poll();
priorityQueueLowest.remove();
priorityQueueLowest.peek();
priorityQueueLowest.element();
priorityQueueLowest.clear();
Priority Queue Using Custom Class
- PriorityQueue 안에 담길 객체를 자신만의 Class로 사용하려면 Comparable Interface를 implements하는 Class를 생성한 후, compareTo method를 우선 순위에 맞게 구현
class Data implements Comparable<Data> {
private int index;
private String content;
public Data(int index, String content) {
this.index = index;
this.content = content;
}
public int getIndex() {
return this.index;
}
public String getContent() {
return this.content;
}
@Override
public int compareTo(Data data) {
if (this.index > data.getIndex())
return 1;
else if (this.index < data.getIndex())
return -1;
return 0;
}
}
public static void main(String[] args) {
PriorityQueue<Data> priorityQueue = new PriorityQueue<>();
priorityQueue.add(new Data(3, "A"));
priorityQueue.add(new Data(4, "C"));
priorityQueue.add(new Data(1, "B"));
priorityQueue.add(new Data(2, "D"));
while (!priorityQueue.isEmpty()) {
Data data = priorityQueue.poll();
System.out.println("index = " + data.getIndex() + ", content = " + data.getContent());
}
}
index = 1, content = B
index = 2, content = D
index = 3, content = A
index = 4, content = C