인프런 커뮤니티 질문&답변
숙제 최소힙 만들기
작성
·
138
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의 값과 비교하는 조건문의 부등호 방향만 바꾸니까 되는데 이게 맞나요...?






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