diff --git a/lib/heapsort.js b/lib/heapsort.js index 69d5af2..968523f 100644 --- a/lib/heapsort.js +++ b/lib/heapsort.js @@ -1,8 +1,14 @@ +import MinHeap from "./minheap"; + // This method uses a heap to sort an array. // Time Complexity: ? // Space Complexity: ? function heapsort(list) { - throw new Error('Method not implemented yet...'); + let heap = new MinHeap; + + while(!heap.isEmpty()) { + list.push(heap.remove()); + } }; module.exports = heapsort; diff --git a/lib/minheap.js b/lib/minheap.js index 4efceaf..9dee22f 100644 --- a/lib/minheap.js +++ b/lib/minheap.js @@ -9,12 +9,17 @@ class MinHeap { constructor() { this.store = []; } - // This method adds a HeapNode instance to the heap - // Time Complexity: ? - // Space Complexity: ? + // Time Complexity: generally Log N + // Space Complexity: equal to the nodes in the heap - 1 + add(key, value = key) { - throw new Error("Method not implemented yet..."); + + const node = new HeapNode(key, value); + this.store.push(node); + if (this.store.length > 1) { + this.heapUp(this.store.length - 1); + } } // This method removes and returns an element from the heap @@ -22,7 +27,13 @@ class MinHeap { // Time Complexity: ? // Space Complexity: ? remove() { - throw new Error("Method not implemented yet..."); + if (!this.store.length) return; + + this.swap(0, this.store.length - 1); + const removed = this.store.pop(); + this.heapDown(0); + + return removed.value; } @@ -41,7 +52,7 @@ class MinHeap { // Time complexity: ? // Space complexity: ? isEmpty() { - throw new Error("Method not implemented yet..."); + return !this.store } // This helper method takes an index and @@ -50,16 +61,42 @@ class MinHeap { // Time complexity: ? // Space complexity: ? heapUp(index) { - throw new Error("Method not implemented yet..."); + + const parentIndex = Math.floor((index - 1) / 2); + const parentNode = this.store[parentIndex]; + const newNode = this.store[index]; + + if (newNode.key < parentNode.key) { + this.swap(index, parentIndex); + if (parentIndex > 0) { + this.heapUp(parentIndex) + } + } } // This helper method takes an index and // moves it up the heap if it's smaller // than it's parent node. heapDown(index) { - throw new Error("Method not implemented yet..."); + const left = 2 * index + 1 + const right = 2 * index + 2 + let smallest = index; + + if((left < this.store.length) && (this.store[left].key < this.store[smallest].key)) { + smallest = left; + } + + if ((right < this.store.length) && (this.store[right].key < this.store[smallest].key)) { + smallest = right; + } + + if (index !== smallest){ + this.swap(index, smallest); + this.heapDown(smallest); + } } + // If you want a swap method... you're welcome swap(index1, index2) { const s = this.store; @@ -67,6 +104,4 @@ class MinHeap { } } -module.exports = { - MinHeap -}; +module.exports = { MinHeap }; \ No newline at end of file