diff --git a/src/data-structures/heap/MinHeap.js b/src/data-structures/heap/MinHeap.js index e768c0b5..40b503aa 100644 --- a/src/data-structures/heap/MinHeap.js +++ b/src/data-structures/heap/MinHeap.js @@ -126,6 +126,8 @@ export default class MinHeap { return 0; } + // Min heap may be converted to max heap by simply changing this line to: + // a > b ? -1 : 1 return a < b ? -1 : 1; } diff --git a/src/data-structures/heap/__test__/MinHeap.test.js b/src/data-structures/heap/__test__/MinHeap.test.js index 99c8861c..04fc06fc 100644 --- a/src/data-structures/heap/__test__/MinHeap.test.js +++ b/src/data-structures/heap/__test__/MinHeap.test.js @@ -26,6 +26,19 @@ describe('MinHeap', () => { minHeap.add(1); expect(minHeap.peek()).toBe(1); expect(minHeap.toString()).toBe('1,3,10,5'); + + minHeap.add(1); + expect(minHeap.peek()).toBe(1); + expect(minHeap.toString()).toBe('1,1,10,5,3'); + + expect(minHeap.poll()).toBe(1); + expect(minHeap.toString()).toBe('1,3,10,5'); + + expect(minHeap.poll()).toBe(1); + expect(minHeap.toString()).toBe('3,5,10'); + + expect(minHeap.poll()).toBe(3); + expect(minHeap.toString()).toBe('5,10'); }); it('should poll items from the heap and heapify it down', () => { @@ -57,4 +70,20 @@ describe('MinHeap', () => { expect(minHeap.poll()).toBeNull(); expect(minHeap.toString()).toBe(''); }); + + it('should heapify down through the right branch as well', () => { + const minHeap = new MinHeap(); + + minHeap.add(3); + minHeap.add(12); + minHeap.add(10); + + expect(minHeap.toString()).toBe('3,12,10'); + + minHeap.add(11); + expect(minHeap.toString()).toBe('3,11,10,12'); + + expect(minHeap.poll()).toBe(3); + expect(minHeap.toString()).toBe('10,11,12'); + }); });