강의

멘토링

커뮤니티

Inflearn コミュニティ Q&A

rhkdtjd124829 のプロフィール画像
rhkdtjd124829

投稿した質問数

非専攻者の専攻者追いつく - 資料構造(with JavaScript)

insertの実装

숙제 최소힙 만들기

作成

·

143

0

class Heap {
  arr = [];

  #reheapUp(index) {
    if (index > 0) {
      const parentIndex = Math.floor((index - 1) / 2);
      if (this.arr[index] > this.arr[parentIndex]) {
        // 값 바꾸기
        const tmp = this.arr[index];
        this.arr[index] = this.arr[parentIndex];
        this.arr[parentIndex] = tmp;

        this.#reheapUp(parentIndex);
      }
    }
  }

  #reheapDown(index) {
    if (index > 0) {
      const parentIndex = Math.floor((index - 1) / 2);
      if (this.arr[index] < this.arr[parentIndex]) {
        const tmp = this.arr[index];
        this.arr[index] = this.arr[parentIndex];
        this.arr[parentIndex] = tmp;

        this.#reheapDown(parentIndex);
      }
    }
  }

  insert(value) {
    const index = this.arr.length;
    this.arr[index] = value; // 마지막에 값을 넣어준다.
    this.#reheapUp(index);
  }

  insertDown(value) {
    const index = this.arr.length;
    this.arr[index] = value;
    this.#reheapDown(index);
  }

  remove() {
    // root만 remove
  }

  search(value) {
    for (let i = 0; i < this.arr.length; i++) {
      if (arr[i] === value) {
        return i;
      }
    }
  }
}

const heap = new Heap();
heap.insert(8);
heap.insert(19);
heap.insert(23);
heap.insert(32);
heap.insert(45);
heap.insert(56);
heap.insert(78);

const downHeap = new Heap();
downHeap.insertDown(78);
downHeap.insertDown(56);
downHeap.insertDown(45);
downHeap.insertDown(32);
downHeap.insertDown(23);
downHeap.insertDown(19);
downHeap.insertDown(8);
console.log(downHeap.arr);

reheapDown 이라는걸 만들어서 최소힙 만들기를 해보았는데 부모 index의 값과 비교하는 조건문의 부등호 방향만 바꾸니까 되는데 이게 맞나요...?

 

javascript코딩-테스트알고리즘

回答 1

1

zerocho님의 프로필 이미지
zerocho
インストラクター

네네 원래 간단합니다

rhkdtjd124829님의 프로필 이미지
rhkdtjd124829
質問者

와우!! 칼답변 감사드립니당 😄

rhkdtjd124829 のプロフィール画像
rhkdtjd124829

投稿した質問数

質問する