[알고리즘] 힙 - JavaScript

2022. 8. 13. 17:39·알고리즘/풀이 힌트
반응형

힙? 

이진 트리 형태를 가지며 우선 순위가 높은 요소가 먼저 나가기 위해 요소가 삽입, 삭제 될 때 

바로 정렬되는 특징이 있다. 

힙의 특징

  • 우선 순위가 높은 요소가 먼저 나가는 특징이 있다. 
  • 루트가 가장 큰 값이 되는 최대 힙과 루트가 가장 작은 값이 되는 최소 힙이 있다. 
  • 자바스크립트에선 직접 구현해야지 사용이 가능하다. 

JavaScript에서 사용하기

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() {
      if (this.heap.length === 2) return this.heap.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;
  }
}

 

더 알아보기 

힙 정렬에 대해서 더 알고 싶다면 [알고리즘] 힙정렬을 보는 것을 추천한다. 

반응형
저작자표시 비영리 변경금지 (새창열림)

'알고리즘 > 풀이 힌트' 카테고리의 다른 글

[알고리즘] 이진 탐색 - JavaScript  (0) 2022.08.17
[알고리즘] 트라이 - JavaScript  (1) 2022.08.15
[알고리즘] 그래프 - JavaScript  (0) 2022.08.12
[알고리즘] 해시 테이블 - JavaScript  (1) 2022.08.09
[알고리즘] Queue - JavaScript  (0) 2022.08.07
'알고리즘/풀이 힌트' 카테고리의 다른 글
  • [알고리즘] 이진 탐색 - JavaScript
  • [알고리즘] 트라이 - JavaScript
  • [알고리즘] 그래프 - JavaScript
  • [알고리즘] 해시 테이블 - JavaScript
잉여개발자
잉여개발자
풀스택 개발자를 목표로 잉여롭게 개발 공부도 하면서 다양한 취미 생활도 즐기고 있는 잉여 개발자입니다.
  • 잉여개발자
    잉여로운 개발일지
    잉여개발자
    • 분류 전체보기 (789)
      • 개발정보 (36)
      • 개발환경 (7)
      • 개발생활 (19)
      • React (141)
        • 이론 (23)
        • 기능 (12)
        • 실험실 (88)
        • 버그 (6)
        • 패스트캠퍼스 (9)
        • Npm (3)
      • React Native (28)
        • 공통 (6)
        • TypeScript (3)
        • JavaScript (18)
        • 버그 (1)
      • Next.js (30)
        • 이론 (13)
        • 실험실 (13)
        • 버그 (3)
      • Web (35)
      • 알고리즘 (202)
        • 풀이 힌트 (39)
      • JavaScript (47)
      • TypeScript (29)
        • 기초 (27)
        • 실험실 (2)
      • Node.js (13)
        • 이론 (0)
        • 기능 (3)
        • 실험실 (9)
        • 버그 (1)
      • 도커 (4)
      • CCNA (22)
        • 이론 (4)
        • 문제 (18)
      • 취미생활 (167)
        • 잉여로운 칵테일 (2)
        • 잉여의 식물키우기 (130)
        • 잉여로운 여행기 (11)
        • 잉여의 제2외국어 (21)
        • 잉여로운 책장 (2)
      • Java (1)
        • Java의 정석 (1)
      • 꿀팁 공유 (3)
  • 태그

    리얼학습일기
    덤프
    javascript
    redux
    CSS
    webpack
    영어독학
    알고리즘
    typescript
    Node.js
    ReactNative
    react
    네트워크
    CCNA
    타일러영어
    ChatGPT
    바질
    다이소
    next.js
    바질 키우기
    리액트
    Docker
    Babel
    영어회화
    네이버 부스트캠프
    프로그래머스
    자바스크립트
    식물
    리얼클래스
    타입스크립트
  • hELLO· Designed By정상우.v4.10.1
잉여개발자
[알고리즘] 힙 - JavaScript
상단으로

티스토리툴바