-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminheap.js
83 lines (76 loc) · 2.28 KB
/
minheap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Heap{
constructor(){
this.items=[];
}
swap(index1,index2){
let temp=this.items[index1]
this.items[index1]=this.items[index2]
this.items[index2]=temp
}
parentIndex(index){
return Math.floor((index-1)/2)
}
leftChildIndex(index){
return index*2+1;
}
rightChildIndex(index){
return index*2+2
}
parent(index){
return this.items[this.parentIndex(index)]
}
leftChild(index){
return this.items[this.leftChildIndex(index)]
}
rightChild(index){
return this.items[this.rightChildIndex(index)]
}
peek(){ //최소 힙의 경우 최솟값 반환 최대힙이면 최댓값
return this.items[0]
}
size(){
return this.items.length
}
}
class minHeap extends Heap{
bubbleUp(){//add시 사용됨
let index=this.items.length-1
while(this.parent(index)!==undefined && this.parent(index)>this.items[index]){
this.swap(index,this.parentIndex(index))
index=this.parentIndex(index)
}
}
bubbleDown(){//pull시 사용됨
let index=0
while(this.leftChild(index)!==undefined &&
(this.leftChild(index)<this.items[index] || this.rightChild(index)<this.items[index])){
let smallerIndex=this.leftChildIndex(index)
if(this.rightChild(index)!==undefined && this.rightChild(index)< this.items[smallerIndex]){
smallerIndex=this.rightChildIndex(index)
//leftchild가 rightchild보다 크면 right<=>item[0]바꿈
//이게 없다면 부모노드에 최솟값 저장 안될수도 있음
}
this.swap(index,smallerIndex)
index=smallerIndex
}
}
add(item){ //힙에 원소 추가하는 함수
this.items[this.items.length]=item
this.bubbleUp()
}
poll(){
let item=this.items[0] //첫번째 원소 keep
this.items[0]=this.items[this.items.length-1]
//맨 마지막 원소를 첫번째 원소로 복사
this.items.pop()//마지막 원소 삭제
this.bubbleDown()//정렬
return item
}
}
const minheap=new minHeap()
minheap.add(1)
minheap.add(1)
minheap.add(2)
minheap.add(1)
minheap.add(8)
console.log(minheap)