|
| 1 | +class Heap { |
| 2 | + heap: Array<number> |
| 3 | + constructor(arr: Array<number>) { |
| 4 | + this.heap = this.buildHeap(arr) |
| 5 | + } |
| 6 | + |
| 7 | + private swap(arr: Array<number>, i: number, j: number) { |
| 8 | + let temp = arr[i] |
| 9 | + arr[i] = arr[j] |
| 10 | + arr[j] = temp |
| 11 | + } |
| 12 | + |
| 13 | + private buildHeap(arr: Array<number>) { |
| 14 | + // builds a heap from an array of elements |
| 15 | + for(let i = Math.floor((arr.length-1)/2); i >= 0; i--) { |
| 16 | + this.heapify(arr, i) |
| 17 | + } |
| 18 | + return arr |
| 19 | + } |
| 20 | + |
| 21 | + insert(element: number) { |
| 22 | + // insert an element into the heap |
| 23 | + this.heap.push(element) |
| 24 | + this.heap = this.buildHeap(this.heap) |
| 25 | + } |
| 26 | + |
| 27 | + delete(index: number) { |
| 28 | + // delete an element from the heap |
| 29 | + this.heap.splice(index, 1) |
| 30 | + this.heap = this.buildHeap(this.heap) |
| 31 | + } |
| 32 | + |
| 33 | + private heapify(arr: Array<number>, index: number) { |
| 34 | + // used when an inserted element unbalances the heap and it loses the heap properties |
| 35 | + // bottom-up approach |
| 36 | + let largest = index |
| 37 | + let left = this.getLeft(index) |
| 38 | + let right = this.getRight(index) |
| 39 | + if ((left <= arr.length) && (arr[left] > arr[index])){ |
| 40 | + largest = left |
| 41 | + } |
| 42 | + if ((right <= arr.length) && (arr[right] > arr[largest])){ |
| 43 | + largest = right |
| 44 | + } |
| 45 | + if (largest != index){ |
| 46 | + this.swap(arr, index, largest) |
| 47 | + this.heapify(arr, largest) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + getMax() { |
| 52 | + // returns the max element in the heap |
| 53 | + return this.heap[0] |
| 54 | + } |
| 55 | + |
| 56 | + pop() { |
| 57 | + // returns the max element in the heap and deletes it from the heap |
| 58 | + let max = this.heap[0] |
| 59 | + this.delete(0) |
| 60 | + return max |
| 61 | + } |
| 62 | + |
| 63 | + private getRight(index: number) { |
| 64 | + return 2 * index + 2 |
| 65 | + } |
| 66 | + private getLeft(index: number) { |
| 67 | + return 2 * index + 1 |
| 68 | + } |
| 69 | + |
| 70 | + // HEAP SORT |
| 71 | + heapSort() { |
| 72 | + // sorts the heap in ascending order |
| 73 | + let tmp = [...this.heap] |
| 74 | + let sorted = [] |
| 75 | + while(this.heap.length > 0) { |
| 76 | + sorted.push(this.pop()) |
| 77 | + } |
| 78 | + this.heap = tmp |
| 79 | + return sorted.reverse() |
| 80 | + } |
| 81 | +} |
0 commit comments