[자료구조] 우선순위큐

2022. 12. 6. 14:25·개발/자료구조
728x90
반응형
 

[자료구조] 이진힙 - BinaryHeap

1. 이진힙이란? 힙이란 모양은 트리와 같다. 트리와는 다르게 힙은 부모와 자식간의 규칙이 있다는 것이다. 최대 이진힙에서는 부모노드가 항상 자식노드보다 큰 값을 가진다. 왼쪽이나 오른쪽

diary-blockchain.tistory.com

1. 우선순위큐

리스트 또는 구조 즉 우리가 데이터를 저장한곳에서 한번에 하나씩 요소를 가지고 온다.

한번에 하나씩 처리를 한 다음에 그 다음것을 처리하게 되는데 병원에 있는 응급실과 비슷하다.

많은 사람들이 대기하고 있고 모두에게는 어느정도의 우선순위가 부여된다.

그러면 간호사나 의사가 와서 한번에 한사람을 그 우선순위에 따라 데려가는것이다.

 

서로 다른 우선순위를 가지는 데이터나 정보를 관리할 필요가 있거나

무언가를 입력하는것이 순서대로 낮은 우선순위를 가지지 않은 경우에 사용할 수 있다.

 

우선순위큐는 힙과 비슷하지만 별개이다.

우선순위큐는 배열이나 리스트를 가지고 만들수도 있다.

 

2. 최대이진힙으로 구현

(1) Node, Class

class Node {
  constructor(val, priority) {
    this.val = val;
    this.priority = priority;
  }
}
class MaxBinaryHeap {
  constructor() {
    this.values = [];
  }
}

(2) enqueue (노드 추가)

enqueue(val, priority) {
    let newNode = new Node(val, priority);
    this.values.push(newNode);
    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.priority <= parent.priority) break;
      this.values[parentIdx] = element;
      this.values[idx] = parent;
      idx = parentIdx;
    }
}

(4) dequeue (노드 삭제)

dequeue() {
    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.priority > element.priority) {
          swap = leftChildIdx;
        }
      }
      if (rightChildIdx < length) {
        rightChild = this.values[rightChildIdx];
        if (
          (swap === null && rightChild.priority > element.priority) ||
          (swap !== null && rightChild.priority > leftChild.priority)
        ) {
          swap = rightChildIdx;
        }
      }
      if (swap === null) break;
      this.values[idx] = this.values[swap];
      this.values[swap] = element;
      idx = swap;
    }
}

 

728x90
반응형

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

[자료구조] 그래프  (1) 2022.12.08
[자료구조] 해시테이블  (0) 2022.12.06
[자료구조] 이진힙 - BinaryHeap  (0) 2022.12.02
[자료구조] 너비 우선 탐색(BFS), 깊이 우선 탐색(DFS)  (0) 2022.11.28
[자료구조] 이진트리  (0) 2022.11.28
'개발/자료구조' 카테고리의 다른 글
  • [자료구조] 그래프
  • [자료구조] 해시테이블
  • [자료구조] 이진힙 - BinaryHeap
  • [자료구조] 너비 우선 탐색(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
    • 팀플
  • 링크

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.1
TeTedo.
[자료구조] 우선순위큐
상단으로

티스토리툴바