Heap
Heap
은 최대값이나 최소값을 빠르게 찾아내기 위해 고안된 자료구조입니다. 힙은 완전 이진트리Complete Binary Tree
의 일종으로, 부모 노드가 자식 노드보다 항상 큰 값최대 힙
이나 작은 값최소 힙
을 가지도록 구성됩니다.부모 노드의 값은 항상 자식 노드의 값보다 크거나 작다.
완전 이진트리이므로, 마지막 레벨을 제외한 모든 레벨이 꽉 차 있어야 한다.
최대 힙의 경우, 루트 노드의 값이 전체 트리에서 가장 큰 값이다.
최소 힙의 경우, 루트 노드의 값이 전체 트리에서 가장 작은 값이다.
힙은 최대값이나 최소값을 찾는 방법에 따라 최대 힙
과 최소 힙
으로 나뉩니다.
최대 힙Max Heap
최소 힙Min Heap
힙은 배열이나 이진트리를 이용하여 구현할 수 있습니다.
배열을 이용한 구현
이진트리를 이용한 구현
힙의 기본 연산에는 삽입, 삭제, 탐색이 있습니다.
삽입Insertion
삭제Deletion
탐색Search
Min Heap
구현public class MinHeap {
private int[] heap; // 배열로 구현한 최소 힙
private int size; // 힙의 크기
public MinHeap(int capacity) {
heap = new int[capacity];
size = 0;
}
public void insert(int value) {
if (size == heap.length) {
throw new IllegalStateException("Heap is full");
}
heap[size] = value;
heapifyUp(size);
size++;
}
public int deleteMin() {
if (isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
int min = heap[0];
heap[0] = heap[size - 1];
size--;
heapifyDown(0);
return min;
}
public boolean isEmpty() {
return size == 0;
}
private void heapifyUp(int index) {
int parentIndex = (index - 1) / 2;
if (index > 0 && heap[index] < heap[parentIndex]) {
swap(index, parentIndex);
heapifyUp(parentIndex);
}
}
private void heapifyDown(int index) {
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
int smallestIndex = index;
if (leftChildIndex < size && heap[leftChildIndex] < heap[smallestIndex]) {
smallestIndex = leftChildIndex;
}
if (rightChildIndex < size && heap[rightChildIndex] < heap[smallestIndex]) {
smallestIndex = rightChildIndex;
}
if (smallestIndex != index) {
swap(index, smallestIndex);
heapifyDown(smallestIndex);
}
}
private void swap(int index1, int index2) {
int temp = heap[index1];
heap[index1] = heap[index2];
heap[index2] = temp;
}
}