-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminheap.ts
More file actions
66 lines (53 loc) · 1.59 KB
/
Copy pathminheap.ts
File metadata and controls
66 lines (53 loc) · 1.59 KB
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
'use strict'
export type BinaryHeapData = number | string // type alias
interface IMinHeap<T> {
insert(node: T): void
getParent(index: number): T | null
getLeftChild(index: number): T | null
getRightChild(index: number): T | null
getMin(): T | null
getSize(): number
}
class MinHeap<T> implements IMinHeap<T> {
private heap: T[]
constructor() {
this.heap = []
}
insert(node: T) {
this.heap.push(node)
this.heapifyUp(this.heap.length - 1)
}
private heapifyUp(index: number) {
const parentIndex = this.getParentIndex(index)
if (parentIndex < 0) return
if (this.heap[parentIndex] > this.heap[index]) {
// swap
const parent = this.heap[parentIndex]
this.heap[parentIndex] = this.heap[index]
this.heap[index] = parent
// recursion
this.heapifyUp(parentIndex)
}
}
private getParentIndex(index: number): number {
return Math.floor((index - 1) / 2)
}
getParent(index: number): T | null {
const parentIndex = this.getParentIndex(index)
return parentIndex >= 0 ? this.heap[parentIndex] : null
}
getLeftChild(index: number): T | null {
const childIndex = (2 * index) + 1
return this.heap[childIndex] ?? null
}
getRightChild(index: number): T | null {
const childIndex = (2 * index) + 2
return this.heap[childIndex] ?? null
}
getMin(): T | null {
return this.heap[0] ?? null
}
getSize(): number {
return this.heap.length
}
}