[DA] Heap

Priority Queue

FIFO ๊ตฌ์กฐ๊ฐ€ ์•„๋‹Œ ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์€ ์š”์†Œ๊ฐ€ ๋จผ์ € ๋‚˜๊ฐ€๋Š” Queue

Heap ์œผ๋กœ ๊ตฌํ˜„ ์ ํ•ฉ

Heap

์ด์ง„ ํŠธ๋ฆฌ ํ˜•ํƒœ

์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์€ ์š”์†Œ๊ฐ€ ๋จผ์ € ๋‚˜๊ฐ€๊ธฐ ์œ„ํ•ด ์š”์†Œ๊ฐ€ ์‚ฝ์ž…, ์‚ญ์ œ ๋  ๋•Œ ๋ฐ”๋กœ ์ •๋ ฌ

Max Heap(๋ฃจํŠธ๊ฐ€ ๊ฐ€์žฅ ํฐ ๊ฐ’), Min Heap(๋ฃจํŠธ๊ฐ€ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’)

Heap ์š”์†Œ ์ถ”๊ฐ€

  1. ์š”์†Œ๊ฐ€ ์ถ”๊ฐ€๋  ๋•Œ๋Š” ํŠธ๋ฆฌ์˜ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ์ •์ ์— ์œ„์น˜
  2. ์ถ”๊ฐ€ ํ›„ ๋ถ€๋ชจ ์ •์ ๋ณด๋‹ค ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’๋‹ค๋ฉด ๋ถ€๋ชจ์ •์ ๊ณผ ์ˆœ์„œ๋ฅผ ๊ต์ฒด

Heap ์š”์†Œ ์ œ๊ฑฐ

  1. ์š”์†Œ ์ œ๊ฑฐ๋Š” ๋ฃจํŠธ ์ •์ ๋งŒ ๊ฐ€๋Šฅ
  2. ๋ฃจํŠธ ์ •์ ์ด ์ œ๊ฑฐ๋œ ํ›„ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ์ •์ ์ด ๋ฃจํŠธ์— ์œ„์น˜
  3. ๋ฃจํŠธ ์ •์ ์˜ ๋‘ ์ž์‹ ์ •์  ์ค‘ ๋” ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์€ ์ •์ ๊ณผ ๊ต์ฒด
  4. ๋‘ ์ž์‹ ์ •์ ์ด ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋” ๋‚ฎ์„ ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณต
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;
  }
}

Categories:

Updated:

Leave a comment