[자료구조] 이진힙 - BinaryHeap

2022. 12. 2. 11:11·개발/자료구조
728x90
반응형

1. 이진힙이란?

힙이란 모양은 트리와 같다.

트리와는 다르게 힙은 부모와 자식간의 규칙이 있다는 것이다.

 

최대 이진힙에서는 부모노드가 항상 자식노드보다 큰 값을 가진다.

왼쪽이나 오른쪽 상관없이 한 레벨 아래에 있는 자식 노드보다 항상 부모 노드가 크다.

형제들 사이에는 특별한 규칙이 없다.

 

최소 이진힙에서는 그 반대이다. 부모 노드가 언제나 양쪽의 자식보다 작다.

이진힙은 언제나 가장 적은 공간을 차지한다.

 

2. 최대 이진힙 구현

(1) 클래스

class MaxBinaryHeap {
  constructor() {
    this.values = [];
  }
}

(2) insert

insert(element) {
    this.values.push(element);
    this.bubbleUp();
}

(3) bubbleUp (순서 정렬)

bubbleUp() {
    let idx = this.values.length - 1;
    const element = this.values[idx];
    while (idx > 0) {
      let parentIdx = Math.floor((idx - 1) / 2);
      let parent = this.values[parentIdx];
      if (element <= parent) break;
      this.values[parentIdx] = element;
      this.values[idx] = parent;
      idx = parentIdx;
    }
}

(4) extractMax (루트 제거 후 마지막 자식 넣어주고 정렬)

extractMax() {
    const max = this.values[0];
    const end = this.values.pop();
    if (this.values.length > 0) {
      this.values[0] = end;
      this.sinkDown();
    }
    return max;
}

(5) sinkDown

sinkDown() {
    let idx = 0;
    const length = this.values.length;
    const element = this.values[0];
    while (true) {
      let leftChildIdx = 2 * idx + 1;
      let rightChildIdx = 2 * idx + 2;
      let leftChild, rightChild;
      let swap = null;

      if (leftChildIdx < length) {
        leftChild = this.values[leftChildIdx];
        if (leftChild > element) {
          swap = leftChildIdx;
        }
      }
      if (rightChildIdx < length) {
        rightChild = this.values[rightChildIdx];
        if (
          (swap === null && rightChild > element) ||
          (swap !== null && rightChild > leftChild)
        ) {
          swap = rightChildIdx;
        }
      }
      if (swap === null) break;
      this.values[idx] = this.values[swap];
      this.values[swap] = element;
      idx = swap;
    }
}

3. 이진힙 빅O

insertion(삽입) removal(제거) search(탐색)
O(logn) O(logn) O(n)

 

728x90
반응형

'개발 > 자료구조' 카테고리의 다른 글

[자료구조] 해시테이블  (0) 2022.12.06
[자료구조] 우선순위큐  (0) 2022.12.06
[자료구조] 너비 우선 탐색(BFS), 깊이 우선 탐색(DFS)  (0) 2022.11.28
[자료구조] 이진트리  (0) 2022.11.28
[자료구조] 스택-큐  (0) 2022.11.28
'개발/자료구조' 카테고리의 다른 글
  • [자료구조] 해시테이블
  • [자료구조] 우선순위큐
  • [자료구조] 너비 우선 탐색(BFS), 깊이 우선 탐색(DFS)
  • [자료구조] 이진트리
TeTedo.
TeTedo.
  • TeTedo.
    TeTedo 개발 일기
    TeTedo.
  • 전체
    오늘
    어제
    • 분류 전체보기 (319)
      • 개발 (274)
        • Article (4)
        • 정리 (21)
        • Spring Boot (17)
        • JPA (2)
        • JAVA (6)
        • Database (4)
        • 자료구조 (11)
        • 알고리즘 (32)
        • React (20)
        • Docker (10)
        • node.js (18)
        • Devops (11)
        • Linux (4)
        • TypeScript (3)
        • Go (10)
        • HyperLedger (4)
        • BlockChain (43)
        • html, css, js (48)
        • CS (3)
        • AWS (3)
      • 모아두고 나중에 쓰기 (3)
      • 팀프로젝트 (18)
        • SNS(키보드워리어) (9)
        • close_sea (9)
      • 개인프로젝트 (1)
        • Around Flavor (1)
        • CHAM (13)
        • ethFruitShop (5)
      • 독서 (0)
        • 스프링부트와 AWS로 혼자 구현하는 웹 서비스 (0)
  • 블로그 메뉴

    • 홈
    • 개발일기
    • CS
    • 실습
    • 코딩테스트
    • 웹
    • Go
    • node.js
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    컨테이너
    CSS
    js
    React
    erc20
    30일챌린지
    go언어
    프로그래머스
    30일 챌린지
    go
    블록체인
    명령어
    node
    mysql
    ERC721
    node.js
    nodejs
    하이퍼레저
    도커
    html
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[자료구조] 이진힙 - BinaryHeap
상단으로

티스토리툴바