자료구조 - 힙(Heap)

시디·2022년 11월 20일
0

자료구조

목록 보기
4/4

힙은 우선순위 큐를 구현하기 위한 가장 좋은 자료구조 이다.

이진 트리 형태를 가지며 우선순위가 높은 요소가 먼저 나가기 위해 요소가 삽입, 삭제 될 때 바로 정렬되는 특징이 있다.

힙 특징

  • 우선순위가 높은 요소가 먼저 나가는 특징을 가진다.
  • 루트가 가장 큰 값이 되는 최대 힙(Max Heap)과 루트가 가장 작은 값이 되는 최소 힙(Min Heap)이 있다.

힙 요소 추가

  • 요소가 추가될 때는 트리의 가장 마지막 정점에 위치
  • 추가 후 보모 정점보다 우선순위가 높다면 부모 정점과 순서를 교환
  • 이 과정을 반복하면 결국 가장 우선순위가 높은 정점이 루트
  • 시간 복잡도 : O(logN)

힙 요소 제거

  • 요소 제거는 루트 정점만 가능
  • 루트 정점이 제거된 후 가장 마지막 정점이 루트에 위치
  • 루트 정점의 두 자식 정점 중 더 우선순위가 높은 정점과 교환
  • 두 자식 정점이 우선순위가 더 낮을 때 까지 반복
  • 시간 복잡도 : O(logN)
class MaxHeap {
    constructor() {
        this.heap = [null];
    }

    push(value) {
        this.heap.push(value);
        let currentIndex = this.heap.length - 1;
        let parentIndex = Math.floor(currentIndex / 2);

        while (parentIndex !== 0 && this.heap[parentIndex] < value) {
            const temp = this.heap[parentIndex];
            this.heap[parentIndex] = value;
            this.heap[currentIndex] = temp;

            currentIndex = parentIndex;
            parentIndex = Math.floor(currentIndex / 2);
        }
    }

		pop() {
        const returnValue = this.heap[1];
        this.heap[1] = this.heap.pop;

        let currentIndex = 1;
        let leftIndex = 2;
        let rightIndex = 3;
        while (
            this.heap[currentIndex] < this.heap[leftIndex] ||
            this.heap[currentIndex] < this.heap[rightIndex]
        ) {
            if (this.heap[leftIndex] < this.heap[rightIndex]) {
                const temp = this.heap[currentIndex];
                this.heap[currentIndex] = this.heap[rightIndex];
                this.heap[rightIndex] = temp;
                currentIndex = rightIndex;
            } else {
                const temp = this.heap[currentIndex];
                this.heap[currentIndex] = this.heap[leftIndex];
                this.heap[leftIndex] = temp;
                currentIndex = leftIndex;
            }
            leftIndex = currentIndex * 2;
            rightIndex = currentIndex * 2 + 1;
        }

        return returnValue;
    }
}
profile
콰삭칩을 그리워하는 개발자 입니다.

0개의 댓글